Sunday, September 19, 2010

dojo.behavior and jquery live

My last blog post mentioned that dojo.behavior was modeled after Ben Nolan's plugin which in turn has since been replaced by jquery.live. After reading this, I made the assumption that jquery's live and dojo.behavior were analagous. Even after coding up a quick example using dojo.behavior to mirror the jquery live() example, I came to the conclusion that these two API methods offered pretty much the same functionality.

However, after a quick discussion on the #dojo IRC channel, Brian Arnold pointed out a subtle but important difference between the two APIs. Apparently, jquery's live method listens for bubbled events on the document element and then maps these events back to jquery.live declarations. dojo.behaviour is a little different. It listens for events fired from the selector on which the behavior is added in the first place. So, if I changed my previous example to look like this:
dojo.behavior.add({
'p': {
onclick: function(evt) {
dojo.place("<p>Another paragraph!</p>", dojo.query('body')[0]);
}
}
});
dojo.behavior.apply();

New paragraphs would only be added when the user clicked on the first 'Click Me' paragraph. However, with jquery, if I altered the original example to look like this:
$("p").live("click", function(){
$("body").after("<p>Another paragraph!</p>");
});

Even clicking on the 'Another paragraph' would result in new p dom nodes being added to the document.

Cheers for pointing out this difference Brian. Also - see the comments below for one other point by Brian.

One other difference between the two APIs was pointed out by Pete Higgins - dojo.behavior includes a 'found' function which operates a little like this:
var myBehavior = {
// all <span> nodes
"span" : {
// for each:
found: function(n){
console.log('this is the first time I have encountered ', n);
}
}
};
dojo.behavior.add(myBehavior);

2 comments:

  1. It's also worth noting that if you do want your new paragraphs to pick up on Dojo behavior definitions, you just need to make a simple dojo.behavior.apply() call, and it'll bind the various event handlers to the new nodes, without doubly binding to the old. :)

    ReplyDelete
  2. @brian. Good point. Amended the original post to reflect this.

    ReplyDelete