Chapter 2 - method dispatch

by Denise Nepraunig

HTML

<link rel="stylesheet" href="http://code.jquery.com/qunit/qunit-1.14.0.css">
<script src="http://code.jquery.com/qunit/qunit-1.14.0.js"></script>
<div id="qunit"></div>
<div id="qunit-fixture"></div>

JavaScript

// 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');
});