jQuery: attaching events to objects

The jQuery's event handling goes far beyond the simple attaching events to HTML elements and allows us to attach events to JavaScript objects. In fact, the $() wrapper works also on objects, thus providing a quick and simple access to object's properties and methods when combined with the bind() method. Let's see the details.

We have the following JavaScript object:

var Class = {

	property: 'Test',
	
	getProperty: function() {
	
		return this.property;
	
	},
	
	setProperty: function(value) {
	
		this.property = value;
	
	}

};

We can attach an event named change to get notified when an object's property changes its value:

$(Class).bind('change', function() {
	
	if(this.property !== 'Test') {
		
		alert('Property changed');
		
	} else {
		
		alert(this.property);
		
	}
	
});

We can use this event with a jQuery's trigger method. Example:

$(Class).triggerHandler('change'); // 'Test'
	
Class.setProperty('Foo');
	
$(Class).triggerHandler('change'); // 'Property changed'

The ideal use for this feature is the Observer Pattern.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.