Skip to content

Instantly share code, notes, and snippets.

@cecilemuller
Created March 4, 2012 14:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cecilemuller/1973168 to your computer and use it in GitHub Desktop.
Save cecilemuller/1973168 to your computer and use it in GitHub Desktop.
jQuery events from non-DOM objects (supports chaining)
/************************
* 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();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment