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() {

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
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()

# and likewise, you can pop those handlers

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:

    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() { ...;; return false; }
} = '.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);
  } = function() {
    // do some more stuff;
    $.events.pop(one, two, three);

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,, …).

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

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:

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() {

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

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:

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, duh, its all in the spirit of an easy read)

function A(name, age) { = name;
  this.age = age;
  this.get_name = function() { return; }
  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; = name;
A.prototype = {
  get_age: function() { return this.age; },
  get_name: function() { return; }

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; = money;
C.prototype = new A;
C.prototype = {
  get_title: function() { return this.title; },
  get_money: function() { return; }

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*


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

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

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

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..