Super easy jQuery events

This post was imported from FARMCode.org which has been discontinued. These posts now exist here as an archive. They may contain broken links and images.

I've been using jQuery for a while but haven't really been using it much in the form of building custom classes or libraries. I've been working on re-developing Umbraco's JavaScript tree using jsTree (which is great by the way!) and have been writing a JavaScript library to support it. As with most code libraries, events play an important role in writing clean and effective code. In the past I've always used simple callback methods for "event handling" in JavaScript, but this isn't really an event system since it doesn't allow more than one subscriber. After some quick research, jQuery has this all built into the core, and by adding a couple very simple methods to your JavaScript classes, they will instantly support an event model!

Quick example: 

var myObject = {
	addEventHandler: function(fnName, fn) {
		$(this).bind(fnName, fn);
	},
	removeEventHandler: function(fnName, fn) {
		$(this).unbind(fnName, fn);
	},
	doSomething: function() {
		$.event.trigger("somethingHappening", [this, "myEventArgs"]);
	}
}

The above example is an object defining 2 functions to manage it's event model and another method which raises an event called "somethingHappened" with an array of arguments that will get bubbled to the event handlers.

To subscribe to the events is easy:

function onSomethingHappening(EV, args) {
	alert("something happened!");
	alert("sender: " + args[0]);
	alert("e: " + args[1]);
}
//subscribe to the event:
myObject.addEventHandler("somethingHappening", onSomethingHappening);

You'll notice that the above event handler function has 2 arguments, one called "EV" and one called "args". The EV parameters is the jQuery event object and the second one is the custom arguments object that was created when raising the event.

Since Umbraco's admin section uses an iframe approach, i though that managing events between the iframes would be an issue since they are all using seperate jQuery instantiations, but by raising and consuming events with the above method, this is no problem.

Author

Administrator (1)

comments powered by Disqus