Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@lifeinafolder
Created December 6, 2011 07:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lifeinafolder/1437282 to your computer and use it in GitHub Desktop.
Save lifeinafolder/1437282 to your computer and use it in GitHub Desktop.
Fun way of doing Observer pattern without maintaining an array of listeners and closely mimicing browser eventing scheme.
// @author: Rajat Mittal
/**
* Sample Model Constructor
* @param {Object} fields
*/
var Model = function(fields){
this._fields = fields;
/**
* NOTICE how we dropped the internal array _listeners
* from previous Gist and used a DOM element.
* Also NOTE that this DOM element is not injected in the DOM.
*/
this.domnode = document.createElement('DIV');
/**
* We also create a custom event using the browser provided
* document.createEvent function now.
* Our custom event is called 'change' accordingly.
*/
this._evt = document.createEvent('Event');
this._evt.initEvent('change',true,true);
};
/**
* Setter function to change each property
* @param {String} key - key name of the property to set
* @param val - new value of the property
*/
Model.prototype.set = function(key,val){
this._fields[key] = val;
// Simply attach the key,val to our custom event object
this._evt.key = key;
this._evt.val = val;
// Dispatch our custom event
this.domnode.dispatchEvent(this._evt);
};
/**
* The new subscribe method.
* It closely mimics browser based event scheme.
* @param {String} eventName - name of the event to subscribe to
* @param {Function} callback - callback listener of the event
*/
Model.prototype.addEventListener = function(eventName,callback){
this.domnode.addEventListener(eventName, callback);
};
/**
* Sample View Constructor
* @param {Object} model - model object to observe
*/
var View = function(model){
this.model = model;
this.model.addEventListener('change', this.listener);
};
/**
* Listener fn that will receive model changes
* @param {Object} event - Event Object
*/
View.prototype.listener = function(event){
console.log('Model property:', event.key, ' changed value to:', event.val);
};
var m = new Model({
name:'Rajat',
age:24
});
var v = new View(m);
m.set('age',26);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment