Is it ok to bind jQuery events to plain, non-DOM Javascript objects:
var myobject = {};
$(myobject).bind("foobar", function() { alert("daa"); });
$(myobject).trigger("foobar");
What are the implications for
Garbage collection (no new references created preventing object to GC'ed)
Object attributes (new attributes assigned to the object)?
Performance
Some things I have noted
The bind() is an inbuilt method in jQuery which is used to attach one or more event handlers for selected element and this method specifies a function to run when event occurs. event: This is an event type which is passed to the selected elements.
Purpose. The event binding allows you to add an event handler for a specified event so that your chosen JavaScript function will be invoked when that event is triggered for the associated DOM element. This can be used to bind to any event, such as keypress , mouseover or mouseout .
bind() method is used for attaching an event handler directly to elements. Handlers are attached to the currently selected elements in the jQuery object, so those elements must exist at the point the call to . bind() occurs.
jQuery error() Method The error() method triggers the error event, or attaches a function to run when an error event occurs.
Instead of using the jquery event system, I would implement one that mimics it using the jQuery.Callbacks method.
var myClass = function(){
this._callbacks = {};
};
myClass.prototype = {
addEvent: function(evname,callback) {
if (!this._callbacks[evname]) {
this._callbacks[evname] = $.Callbacks();
}
this._callbacks[evname].add(callback);
},
removeEvent: function(evname) {
if (!this._callbacks[evname]) {
return;
}
this._callbacks[evname].remove();
//Might need this too:
//this._callbacks[evname] = null;
},
triggerEvent: function(evname) {
if (this._callbacks[evname]) {
this._callbacks[evname].fire();
}
}
};
var foo = new myClass();
foo.addEvent("foo",function(){
console.log('foo');
});
foo.triggerEvent("foo");
foo.removeEvent("foo");
// event was removed, the below line won't do anything.
foo.triggerEvent("foo");
http://jsfiddle.net/kEuAP/
However, to answer your question, I don't see any immediate problems with what you are doing other than it isn't documented and may change functionality from version to version (although it works in all currently available versions 1.2.6+).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With