Click to change color scheme

Notes on codes, projects and everything

Maintaining State with jQuery Event

Maintaining state in Javascript is not too difficult once you catch the idea. However, as I am not a super brilliant programmer, it takes me some time to find a way to maintain state as YUI Event does in jQuery.

I like grouping relevant functions into a class as it makes code easier to manage (for me, as there may be better ways. As I just recently found out how prototyping inheritance works, it is possible that the discovery may change the way I code in future), therefore the scope of event handler functions is very important. Making the scope (value/reference of this) to the DOM element listened to the event does not help in accessing the shared data so I needed a way to change that behavior.

To solve the problem, a small derivation of the previously discussed delegate function will come in useful.


/**
 * Simulating YUI Event with jQuery
 */
(function($) {
EventHandler = function(_method, _scope) {
    var _argument = {};
 
    if(arguments.length > 2) {
        _argument = arguments[2];
    }
 
    // jquery default event callback format
    return function(_event) {
        // this = DOM element
        return _method.call(_scope, _event, this, _argument);
    };
};
})(jQuery);
 
var Foo = function() {
 
    var bar_handler = function(_event, _element) {
        alert('bar');
    }
 
    var foo_handler = function(_event, _element, _extra_argument) {
        alert(_extra_argument);
    }
 
    (function() {
        $('#foo').click(EventHandler(foo_handler, this, 'foo'));
        $('#bar').click(EventHandler(bar_handler, this));
    }).call(this);
};
var foo = new Foo();

That basically wraps up what I found these couple of days, if I manage to dig some time, the next post should be focused on prototypical inheritance.

leave your comment

name is required

email is required

have a blog?

This blog uses scripts to assist and automate comment moderation, and the author of this blog post does not hold responsibility in the content of posted comments. Please note that activities such as flaming, ungrounded accusations as well as spamming will not be entertained.