jQuery and the Observer Pattern: monitoring objects with custom events

jQuery and the Observer Pattern: monitoring objects with custom events

How to implement the Observer Pattern in jQuery by using custom events.

The jQuery event model can also be extended to traditional JavaScript objects. A common use is surely monitoring the state of an object in order to notify the rest of the application when a change in the object's state occurs. This behavior is often implemented by using the Observer Pattern.

Let's start with a simple object:


var Class = {

    property: 'Test',

    getProperty: function () {

        return this.property;

    },

    setProperty: function (value) {

        this.property = value;

    }

};

When you set a new value for the property member the current state of the object obviously changes:


Class.setProperty('Bar');
console.log(Class.property); // 'Bar'

We need to monitor these changes by defining a custom event on the object itself:


$(Class).on('change', function () {

    if (this.property !== 'Test') {

        console.log('Property changed');

    } else {

        console.log(this.property);

    }

});

The .on() event method is here used by passing the object to the $() wrapper method. The jQuery wrapper works both on normal element objects and traditional JavaScript objects. Our final step is to trigger this custom event when a change takes place:


setProperty: function(value) {
    this.property = value;
    $(Class).triggerHandler('change');
}

Example:


console.log(Class.getProperty()); // 'Test'

Class.setProperty('Bar'); // 'Property changed'

[view-example url="http://jsfiddle.net/gabrieleromanato/a9dwD/"]