Skip to content

Instantly share code, notes, and snippets.

@yavor-atanasov
Created March 21, 2011 23:34
Show Gist options
  • Select an option

  • Save yavor-atanasov/880477 to your computer and use it in GitHub Desktop.

Select an option

Save yavor-atanasov/880477 to your computer and use it in GitHub Desktop.
Illustrating the quirks of jQuery's trigger method when using non-DOM objects
/**
jQuery's trigger() behaves in the following way:
1. Execute all callbacks bound using the bind() method in first-in-first-out order.
2. Check for a method called ('on' + eventType) e.g. "onfoo" and execute it as well
3. Check for a method called (eventType) e.g. "foo" and execute it as well
*/
require(["jquery-1"], function($) {
var Gadget = function(){
$(this).bind('foo', function(){
console.log("You've been fooed'")
});
}
Gadget.prototype.onfoo = function(){
console.log("You've been fooed again'");
};
Gadget.prototype.foo = function(){
console.log("You've been fooed yet again'");
};
var myGadget = new Gadget();
/**
This will execute all the three console.logs
*/
$(myGadget).trigger('foo');
});
/**
This becomes an issue in the following situation:
Gadget has two methods - changedata() and changeagain() that change the value of the data variable.
We bind them to the 'changedata' event using bind();
When we trigger the 'changedata' event, the logic would lead us to believe that
first the data var will be set to 0 and then it will be set to 1.
However, since the name of the changedata() method is the same as the event's name,
it will be called again after all bound callbacks are executed. This means that data will be
set to 0 again at the end.
*/
require(["jquery-1"], function($) {
var data;
var Gadget = function(){
$(this).bind('changedata', this.changedata);
$(this).bind('changedata', this.changeagain);
}
Gadget.prototype.changedata = function(){
data = 0;
};
Gadget.prototype.changeagain = function(){
data = 1;
};
var myGadget = new Gadget();
$(myGadget).trigger('changedata');
// Outputs 0
console.log(data);
});
@yavor-atanasov
Copy link
Copy Markdown
Author

This became an issue for me when working on the Autosuggest widget. The Autosuggest's prototype has a method dataready() that is bound to the 'dataready' event. This dataready() method clears all (previously) appended result list items. At the same time the 'dataready' event is exposed to people to bind to and append new result list items when the event is triggered. And since the dataready() method was executed again after all bindings, the newly added result items were removed immediately after they were added.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment