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.

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

Javascript’s not all bad

I gotta admit, through all the frustration and experimentation ive gone through with the language recently, its not so bad. At first I thought, “expressive? no way” b/c it seems like when you go to be expressive, you crop up with irreparable errors that eventually force you into one “expression”. Frustration follows each step, as is learning for me, yet I carry on.

Now Im feeling the chains loosened. Not so much do I feel tied to a particular paradigm when writing out bits of javascript, particularly, paradigms that Ive brought over from projects Ive worked on in python. Im looking at new ways to do things in javascript, in particular I was pretty happy to see getters and setters in javascript 1.5, Ive always enjoyed them for a couple reasons.

Getters and Setters provide a consistent API
Alot of times, we find ourselves writing utilities and libraries of utilities to perform particular actions. When using these libraries (or someone else’s for that matter), its important to have a consistent API so one can think about the task at hand, not the details of the API. If you have a series of attributes on an object, but some of them might be dependent on others, getters and setters might prove useful for consistency in accessing object properties. If you have the following properties, parent, children, x, y, w, h, batch, visible, well keeping in mind to call get_parent() or batch() or whatever while calling .w and .visible for others really blows. All I can say is that I hope theres auto generated documentation to keep at hand, which will be a pain if theres long time periods in between using the library.

Getters and Setters provide a mechanism for error checking
Another use I’ve found for getters and setters is error checking. It provides a centralized point to assert the value is something valid before getting or setting. So say I have

widget.x = input

Theres alot of places I could check input, but if Im getting input and setting x from different scenarios that crop up, being able to check it with a setter on x would consolidate alot of code.

Anyway, having access to getters and setters in javascript will be useful to say the least. Embracing the functional style of javascript looks like a win-win situation. Unlike others, I have no gripes with calling object.prototype.method.call(this) but even that is probably unnecessary in alot of situations, trying to fit a bull with a shoehorn.

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”});

Baffling Results from my Javascript Class(-ishness)

** Edit, regarding the following, I suddenly realized what the problem was, .call is slow and was used in the “native” approach. Nevertheless Ive had positive result following through on multiple inheritence and magic methods. refer here, http://wp.me/piHZk-14 **

Ok, So recently I’ve taken an interest in javascript. By interest I mean taking it more seriously as a language. One of the first things I wanted to do was to see if I should adopt a framework like mootools to allow for classical inheritance type of stuff or if I should develop using the prototypal javascript inheritance. This lead me to really dig in deep to javascript scope and all of its nuances, especially considering prototype.

Along the way, pecking away at my smjs console (aptitude install spidermonkey-bin), I eventually wrote this function class() {} as I was trying to see what I could get away with in poking at the scope of functions and their prototypes. I was particularly annoyed with a seperation between the constructor and that which was prototyped and the foresight required, which Im going to lack since Im new to the game. Anyway, heres the function,

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

effectively, this allowed me to write my prototypes in the constructor as well as extend functions. It was all in the name of learning and I wasn’t considering it practical. So basically I wrote stuff like

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

class(A, object)
function A(kwargs) {
    this.init(kwargs);
}

var a = new A({name: "Daniel", age: "24"});

I was also playing around with object constructors (unsuccessfully) curious as to if i could implement magic methods that could be inherited and run automatically, but yeah, that went no where so i was all but about to abandon this whole excursion when I decided, before I do, I wonder how much more memory my function class() {} uses and how much slower it is from doing it the standard way. By standard, I mean what I basically learned from perusing the net and from MDC javascript 1.5 Engineering Model Example. Heres what I have for the “standard” way

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

function A(kwargs) {
    object.prototype.init.call(this, kwargs);
}

var a = new A({name: "Daniel", age: "24"});

Now my profiling isn’t very scientific I suppose, I used top and timed the execution from within javascript, but the results are consistent. What I basically did was this

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

load('test2.js');
var l = [];
for (var j = 0; j < 5000; ++j) {
    l.push(new A({name: "Daniel", age: "24"}));
}

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

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

where load(‘test2.js’) was the “standard” way and load(‘test4.js’) in a seperate file was my way. The first thing that caught me off guard was that memory consumption was the exact same. I was half expecting my method to take more memory b/c the function definations existed in two places, but I guess the javascript runtime compiler doesn’t cause this to happen, so yippie freaggin do da. Now what left me baffled was that my way was consistently faster then the standard way. Here are the time results, running 10 in a row

* all times are in milliseconds
=== Standard ===
54
58
49
55
55
53
53
49
53
52

=== My Way ===
42
41
42
45
45
42
42
48
48
48

The numbers were close, so then i decided to increase the number of objects created to perhaps provide a more significant and visible difference. So I increased the number of objects from 5,000 to 500,000.

=== My Way ===
5716
4257
4229
4331

=== Standard Way ===
7601
4866
4913
5564

Its as if the javascript compiler runs faster instantiating an object property and linking it to a prototype then it does when just instantiating a prototype property. And it doesn’t require any extra headway in memory to do it.

If theres any javascript ninja’s that can explain whats going on, thatd be simply awesome. Speaking of which, im gonna go find mailing list now…

CherryPy, SndObj, and SVG

Ok so sometime back when i first started tinkering with pysndobj, i was toying with some ideas for a user interface. Primarily i come from a web background and i decided to toy with the idea of a web frontend to a sndobj thread(s) that would write to an output stream that multiple people could connect to to work collaboratively together semi-realtime. Yeah, it sounds a bit amibitious but anyway I decided to take the time to toy around with SVG as well, which ive never worked with, to see what I might come up with.

Ultimately, I got this, cpsndobj.

This is the source code to my simple cherrypy/sndobj/svg demo. Basically I have an svg knob that i made that you can manipulate by clicking and dragging the mouse down on it. Unfortunately with a browser you cannot lock the mouse down in place so it can seem a bit odd if you reach the edge of your screen. But anyways, tar -xzf this bad boy and ./python cpsndobj.py and you will find a local webserver at http://127.0.0.1:8080/. Of course you need to sudo easy_install-2.5 cherrypy if you wanna use it. The rest is javascript(jquery if i remember correctly(been a while since i looked(i think this is why i like python, avoiding all these tags(woot!)))). And I believe I have it set to connect to a jack server so you’ll want to change it to SndRTIO if you want otherwise or start your jack first. After you get it up and running, visit the local address /on to turn on the modulating frequency the visit the root of the site to display the svg knob. Now click and drag it. and youll see it do its thing. Things to note, if your using internet explorer, you’ll need to install the adobe svg viewer (though ive not tested it in IE). Here in firefox land, we apparently like things to run slow so if youd like to experience a smooth svg knob .. experience, then get opera installed and notice the difference.

Uh but yet, i dont use opera past playing with an svg knob and playing flash movies that dont lock up my browser in linux.

One might say, ultimately i basically have a tinker toy thats ok (woot!).

–Edit: I suddenly realized the fallacy of my “i like python” statement above, python still has paranthesis.. duh..