Binding (and unbinding) JQuery Event Handlers in a Complex Web App

I’m commonly placed in a tough situation. Here I am, working on a web related project and I would like to implement a lot of complex features via javascript. JQuery is the first library I’ve used and it has allowed me to at least dream of a functional, yet complex, web application. Typically, the first 25% of the javascript related work is a total breeze, thanks to jquery. The next 30-50% of the work becomes totally convulated, thanks to jquery being my crutch, and never diving in and bothering to understand javascript all these years. The final percent is ussually left on a wish-list of too-buggy-to-deploy and wouldn’t-it-be-nice.

Here I am again, endeavoring to build a complex and functional web application and this time I really want to get it right, and low and behold, I’m beginning to run into one of those typical problems.

Binding Events with JQuery

JQuery really makes this easy. I love it. I remember first starting off and writing a little bit of code like this:

$('.button').click(function() {
  $.get('/some/stuff', function() {
    $('.somestuff').append(....);
  });
});

and what not. Then I discovered that beloved .load() function. Really cut down on a lot of legwork I was doing. But there was always a slight problem. I always ended up with conflicting binds. There were various ways I worked around this, among other problems before .live() was around, but it was always a bit of a conundrum. I think this mostly deals with the approach JQuery takes towards usability. The focus is quickly accessing an object and binding the specified event, nothing more. It makes no effort to force any sort of design paradigm, which leads me to wonder, how should I handle this? I figure the first place to look for inspiration are in libraries I already currently use that solve this sort of design pattern.

Pyglet Event Handling for OpenGL/Python

I’ve used pyglet for a while now. It has a few design patterns for handling events that go something like this:

# first, it allows for decorators over a method
@windows.event
def mouse_press(...):
    pass # and do stuff

# and also a window method to push handlers of class instances
class SomeStuff(object):
    def mouse_press(...):
        pass # and go

some_stuff = SomeStuff()
window.push_handlers(some_stuff)

# and likewise, you can pop those handlers
window.pop_handlers(some_stuff)

The first design pattern doesn’t really solve any particular problem of mine and is pretty much already what is going on using jquery events. But the second pattern is something I would have considered impossible for me to accomplish in javascript, I’ve just never understood the language enough to consider it doable. But recently, I’ve been coming to understand the language a lot more and wrote a small utility for making better use of prototypal inheritance in javascript, js.js, and it struck me that this would be pretty easy to implement.

A Design Paradigm for JQuery Event Handling

First, its important to understand a small bit about the js.js utility. It’s somewhat based off of Crockford’s function that prototyped an empty constructor with a passed in object. The difference here is that js.js calls magic methods (instead of being an empty constructor) and allows one to pass in multiple objects and functions to be prototyped.

The design consists of two parts. A jquery plugin in the form of $.events.push() and $.events.pop() and a prototype inheritance pattern, optionally using the js.js function.

This is the plugin code:

$.extend({
    events: {
        recurse: function(args, action) {
            for (var x in args) {
                var obj = args[x];
                for (var k in obj) {
                    if (typeof obj[k].bind != "undefined") {
                        if (action == "push") {
                            $(obj[k].bind).bind(k, obj[k], obj);
                        } else {
                            $(obj[k].bind).unbind(k, obj[k]);
                        }
                    } else if (typeof obj[k].live != "undefined") {
                        if (action == "push") {
                            $(obj[k].live).live(k, obj[k], obj);
                        } else {
                            $(obj[k].live).die(k, obj[k]);
                        }
                    }
                }
            }
        },
        push: function() {
            this.recurse(arguments, "push");
        },
        pop: function(obj) {
            this.recurse(arguments, "pop");
        }
    }
});

The scenario is this. A lot of ajax events are very similar and would work across different loaded pages/forms. Where necessary, one could override an event to add extra functionality:

controls = {
  index: function(params) { $(...).load(...); },
  form: function(params) { $(...).load(...); },
  save: function(data) { $.post(..., this.index); }
}

events = {
  keyup: function() { ... },
  submit: function() { ...; this.save(data); return false; }
}
events.keyup.live = '.main .filter'; // just demonstrating access to live and bind
events.submit.bind = '.main .form';

user = function() {
  this.init = function() {
    $('a[href=#user]').bind('click', this.click, this);
  }
  this.click = function() {
    highlight(...);
    // do some more stuff;
    this.index();
    this.form();
    
    $.events.pop(one, two, three);
    $.events.push(this);
  }
}

var User = prototype(user, events, controls, object);

$(function() {
  var u = new User({url: '/db/User'});
});

This allows for common parts to be factored out when shared by many different objects. Picture five other objects alongside User. Some might override events and call the original, for example, events.submit.call(this, …).

This is a little rudimentary to start, but its a start none-the-less.

Advertisements

A New Way to Prototype with Javascript

Ive been doing alot of reading. One place that I keep happening upon is Crockford’s javascript pages. I dont reallly know who that is, but I’ve occasionally read he’s some sort of javascript legend. Well, I was looking over one of his pages, describing instantiating new objects, specifically:
http://javascript.crockford.com/prototypal.html

He talked about prototypal behavior, how it should work, and his simple function for doing so. Effectively, creating a blank function definition and then setting its prototype to the passed in object. I suddenly realized something. Ive been going about it all wrong with this class() business. Furthermore, what I had in place was his function but on steroids. Instead of initializing a blank function, I have what i was considering a sort of meta object that links to magic methods. And instead of setting the prototype to the object passed in, I set it to the all the objects passed in. So I took this thought and made some minor changes to the code, including being able to pass in objects, not just functions. Now I can write stuff like this,

x = {get: function() { return this.url; }};

function y() {
    this.get_url = function() {
        return x.get.call(this);
    }
};

var super_object = prototype(y, x);

and now super_object has the methods of y and x, where the order of the arguments decides precedence of inheritance. So I can create a new instance by

var a = new super_object({url: '/test/this'});
a.get_url() // returns '/test/this'
a.get() // returns '/test/this'

There some behind the scenes action here. What I did was abstract out the meta object with the intention of overriding it. But on some more thought, I think I will simply make it explicit, this way one could define any number of meta objects with their own magic methods, or if it so fits, simply pass in a blank function() {}, following Crockford’s lead. So it would look more like

var super_object = prototype(y, x, meta); // or whatever you call your meta, or
var super_object = prototype(y, x, function(){}); // for no magic methods or special constructors

Speaking on speed, Its important to note that there are no call’s or apply’s ever, though thats not to say one couldn’t write it into a custom meta object. Point being, it runs fast, just as fast as typing it all out manually. It doesn’t strive to be “classical” in any way. It simply focuses on custom constructors for multiple objects and a simple way to combine multiple objects, given order of precedence of arguments. It could be just as easily used in conjunction with explicit prototypal declarations. Seems like a win-win for keeping it simple.

*** Edit *** I forgot to mention, in the above example, x is an object that super_object inherited, but say you override x’s method and then needed to call it? well its a good bit shorter since its already an object, simply

x.get.call(this)

No need for specifying the prototype. I think this could easily become a simple design paradigm I might follow, Ill need more experience to judge properly though

*** Edit2 *** Heres a link to the code

Whats wrong with javascript prototype?

** Edit **You can see my current approach to these frustrations here: http://js.dasa.cc

O thats easy, ok lets write up a base object we’ll want to inherit from (note, I would not actually write a this.get_name to retrieve a this.name, duh, its all in the spirit of an easy read)

function A(name, age) {
  this.name = name;
  this.age = age;
  this.get_name = function() { return this.name; }
  this.get_age = function() { return this.age; }
}

Good, ready? oh shit, wait a sec, according to MDC we were being naive. Now the only way to call the get_name and get_age functions is with an instance of A. Well crap, that doesn’t help inheritance much, prototypal or not. Alright so lets do this right.

function A(name, age) {
  this.age = age;
  this.name = name;
}
A.prototype = {
  get_age: function() { return this.age; },
  get_name: function() { return this.name; }
}

Yeay, yippie for us, now lets extend A with B

function B() {};
B.prototype = new A;

Yeay, yippie, now lets make C with an extra param and function and extend A.

function C(name, age, title, money) {
  this.title = title;
  this.money = money;
};
C.prototype = new A;
C.prototype = {
  get_title: function() { return this.title; },
  get_money: function() { return this.money; }
}

Good? alright lets.. o crap! it doesn’t work. Right, right, thats right, I totally erased the A prototype by using the prototype = {} syntax, ok so that syntax is no good for working with inheritance unless its the top level thing, but crap, i dont wanna think about that. Whatever, lets just fix C for now though readability will be a little funky, hey .. i know! lets just say if i use the prototype = {}; syntax, thats a way to differentiate it as a top level parent! yeah! thats great justification *cough*not*cough*

anyway

function C(name, age, title, money) {
  this.title = title;
  this.money = money;
};
C.prototype = new A;
C.prototype.get_title = function() { return this.title; }
C.prototype.get_money = function() { return this.money; }

ok, lets fire this bad boy up and test C.. Where the hell is my name? and age!? son of a.., I see, so i need to manually call the constructor of the same damn thing that I C.prototype=’d

alright, its cool, lets fix it, I can dig it. Lets add that A.call

function C(name, age, title, money) {
  A.call(this, name, age);
  this.title = title;
  this.money = money;
};
C.prototype = new A;
C.prototype.get_title = function() { return this.title; }
C.prototype.get_money = function() { return this.money; }

Sweet buttery buttons! It works! wait a sec.. why is this code running slower then before? Yeah yeah, theres creating the name and age now that wasn’t before but its more… its .call() ! Wth?! why is this causing it to go slower? Alright alright, its cool, lets just… migrate these object property inits out of the contructor and into a prototype function that will handle the needs of all that inherit it since its mostly the same.

Ah hell, im hungry, maybe another day..

A Javascript Class with magic methods

Hey, ok so this is what i have so far, totally preliminary

function class() {
    var that = function() {
        this.__init__(arguments[0]);
    };
    that.prototype = new object;

    for (var x=arguments.length-1; x>=0; --x) {
        var m = new arguments[x];
        for (var i in m) { that.prototype[i] = m[i]; }
    }
    this[arguments[0].name] = that;
}

function object() {
    this.__init__ = function(kwargs) {
        for (var k in kwargs) {
            this[k] = kwargs[k];
        }
    }
}

Short, right?

Then I can write something like this,

class(A, object)
function A() {
    this.get_name = function() {
        return this.name;
    }
}

class(B, A)
function B() {
    this.get_age = function() {
        return this.age;
    }
}

class(C, object)
function C() {
    this.__init__ = function() {
        this.name = "OVERRIDE";
    }
}


var a = new A({name: "Daniel", age: "24"});
var b = new B({name: "David", age: "25"});
var c = new C({name: "John", age: "26"});

effectively just sticking a little header over normal javascript functions, and everything works as one would expect.

a.name // returns Daniel
a.age // returns 24
b.get_age() // returns 25
b.get_name() // returns David
c.name // returns OVERRIDE

And to boot, it executes at the same speed as writing it the “native” way. Here’s what i have for “native” (im a noob so correct any errors)

function object() {}
object.prototype.init = function(kwargs) {
    for (var k in kwargs) {
        this[k] = kwargs[k];
    }
}

function A(kwargs) {
    this.init(kwargs);
}
A.prototype = new object;
A.prototype.get_name = function() {
    return this.name;
}

function B(kwargs) {
    this.init(kwargs);
}
B.prototype = new A;
B.prototype.get_age = function() {
    return this.age;
}

function C() {
    this.name = "OVERRIDE";
}

I ran a test importing each implementation, respectively, and got similar results in execution speed and memory size. I created 100,000 thousand objects of each A, B, C and each method occupied 78mb according to top, and each method consistently ran between 2100-2300 ms with variance that occasionally hit 3000 ms. Ultimately its not surprising as all the class function i wrote does is auto write how you would do it natively. What Im surprised about is theres no extra cruft when the javascript runtime compiler handles it. I never intended this to be useful, it was all part of an experiment delving into javascript scope and messing with constructors so i could evaluate the use of a library like prototype.js or mootools.

But hell, so far this little bit of code is turning out to be fairly useful. I imagine if i write more magic methods, the memory size will increase by a small amount. I half expected to see a difference in memory since the C is much more stripped down in “native” version vs the version with __init__ cruft from object function.

This has all been using spidermonkey-bin (smjs) so now im curious to see how other javascript implementations handle the details, as from the get-go i expected a huge increase in memory (not that I know anything about anything) from functions existing in the constructor and then being linked to a prototype, and all those “new” instances called in class. But it all seems negligible, in spidermonkey anyway. This could be a totally different story in IE, lol

for reference, heres my lame-o profile code (i know, i know, but it was enough to find all sorts of issues when exploring javascript scope and constructors)

var date1 = new Date(); 
var milliseconds1 = date1.getTime(); 

load('custom.js'); // point this to which script to test
var l = [];
for (var j = 0; j < 100000; ++j) {
    l.push(new A({name: "Daniel", age: "24"}));
    l.push(new B({name: "David", age: "25"}));
    l.push(new C({name: "John", age: "26"}));
}

var date2 = new Date(); 
var milliseconds2 = date2.getTime(); 

var difference = milliseconds2 - milliseconds1;
print(l.length)
print(difference)

*** EDIT *** Also, function object needs a class(object) so you can call its magic methods, so in C this.__init__ = function(kwargs) { object.prototype.__init__.call(this, kwargs) }
Of which, im a little confused, b/c I originally expected to not work. Anytime a Class(X) is called, its constructor gets replaced, so another Class(X) later on will be referring to that replaced class which i thought would cause some kind of error, or so i would think. So deep inheritance might cause some bad mojo with the amount of memory or hell if i know. I haven’t looked into that yet
*** EDIT 2 *** Also, im not sure how much of a “class” this is really, if it turns out useful i may find a different name, maybe just call it “prototype” so like
prototype(A, object)
function A() {};
var a = new A({name: “daniel”});