/ Published in: jQuery
**Important: this snipplet has moved to Github.**
- [jQuery events from non-DOM objects (supports chaining)](https://gist.github.com/1973168)
- [jQuery events from non-DOM objects (supports chaining)](https://gist.github.com/1973168)
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/************************ * Class definition ************************/ var MyObjectClass = function(parameters){ var $ = jQuery; var context = this; /** * Detached element used to tap into the regular jQuery events model. * @private */ var _events = $(document.createElement('span')); /** * Attaches a handler to an event for the class instance. * @param eventType String A string containing one or more JavaScript event types, such as "click" or "submit," or custom event names. * @param handler Function A function to execute each time the event is triggered. * @see http://api.jquery.com/bind/ */ this.bind = function( eventType, handler ){ //_events.bind(eventType, handler); // older jQuery versions _events.bind(eventType, $.proxy(handler, context)); // jQuery 1.4 and newer return this; }; /** * Removes a previously-attached event handler from the class instance. * @param eventType String A string containing a JavaScript event type, such as click or submit. * @param handler Function The function that is to be no longer executed. * @see http://api.jquery.com/unbind/ */ this.unbind = function( eventType, handler ){ //_events.unbind(eventType, handler); // older jQuery versions _events.unbind(eventType, $.proxy(handler, context)); // jQuery 1.4 and newer return this; }; /** * Executes all handlers and behaviors attached to the class instance for the given event type. * @param eventType String A string containing a JavaScript event type, such as click or submit. * @param extraParameters String An array of additional parameters to pass along to the event handler. * @see http://api.jquery.com/trigger/ */ this.trigger = function( eventType, extraParameters ){ _events.trigger(eventType, extraParameters); return this; } // //... // /** * Example public method to make the object send an event of type <code>my_event</code>. */ this.test = function(){ _events.trigger("my_event"); }; }; /************************ * Usage example ************************/ // Creates an instance of the class var obj = new MyObjectClass(); // Listens to the event the same way you would with DOM elements obj.bind( "my_event", function(e){ console.log("The custom event has been received"); } ); // Makes the object fire an event obj.test();