// Programming JavaScript Applications
// Chapter 2
// method dispatch
/* what to do when an objects receives a message JS checks this by checking if the objects has this method, it continues to search on the prototypes. */
// this is used in jQuery stuff like
// $(selection).yurPlugin('methodName', params);
var methods = {
init: function (args) {
return 'initializing...';
},
hello: function(args) {
return 'Hello ' + args + '!';
},
goodbye: function(args) {
return 'Goodbye cruel ' + args;
}
},
greet = function greet(options) {
var args = [].slice.call(arguments, 0),
initialized = false,
action = 'init'; // init will run by default
if (typeof options === 'string' &&
typeof methods[options] === 'function') {
action = options;
args.shift();
}
return methods[action](args);
};
QUnit.test('Dynamic dispatch', function(assert) {
var test1 = greet(),
test2 = greet('hello', 'World'),
test3 = greet('goodbye', 'world');
assert.equal(test1, 'initializing...',
'Dispatched to init method');
assert.equal(test2, 'Hello World!', 'Dispatched to hello method');
assert.equal(test3, 'Goodbye cruel world',
'Dispatched to goodbye');
});
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.