jQuery Data Binding

Use .on() .off() and .trigger() on data objects.

Fork me on GitHub

This is a simple way to use jQuery event handling inside objects for data binding, Observer, Pub/Sub stuff. Just use the classic module pattern built on top of an empty jQuery Object.

Here’s a simple example and some code:

Simple Example

Cool factor

0

To create a data or app object with jQuery-style event handling, extend an empty jQuery object.

					
	var dataObj = $.extend($({}),(function(o) {

		// Private Things
		var coolFactor = 0;

		function isCoolStuff(stuff) {
			return stuff.indexOf('cool') != -1;
		}

		// Public Things
		o.doStuff = function(stuff) {
			if (isCoolStuff(stuff)) {
				coolFactor++;
				o.trigger('did.it',[{done:stuff, status:coolFactor}]);
			} else {
				--coolFactor; // we only do cool stuff!
				o.trigger('did.nothing',[{status:coolFactor}]);
			}
		};

		return o;

	})($({})));
					
				

Then you can define triggers and event handlers for passing data to and from your data object and the DOM. Basically this is like building your own tiny custom Angular.js type thing.

					
	// DOM event handlers
	$('#button').on('click',function() {
		dataObj.doStuff(Math.random() > 0.4 ? 'cool stuff' : 'boring stuff');
	});

	// Data event handlers with chaining and namespaces (thanks jQuery)
	dataObj
		.on('did.it',function(e, data) {
			$('#output').prepend('

We did '+data.done+'. (+1)

'); }) .on('did.nothing',function() { $('#output').prepend('

We did nothing. (-1)

'); }) .on('did.it did.nothing',function(e, data){ $('#status').text(data.status); });

Other Approaches