Created
December 6, 2011 07:50
-
-
Save lifeinafolder/1437251 to your computer and use it in GitHub Desktop.
Textbook Observer Pattern Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Extremely naiive implementation of Observer pattern | |
* Its used to illustrate the concept and to basically show | |
* How its done. This is not production level code. | |
* @author: Rajat Mittal | |
*/ | |
/** | |
* Sample Model Constructor | |
* @param {Object} fields | |
*/ | |
var Model = function(fields){ | |
this._fields = fields; | |
this._listeners = []; | |
}; | |
/** | |
* Subscribe method can be used to subscribe | |
* to this model to listen to changes on it. | |
* @param {Function} cbk - function to invoke to inform | |
*/ | |
Model.prototype.subscribe = function(cbk){ | |
this._listeners.push(cbk); | |
}; | |
/** | |
* 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; | |
this._listeners.forEach(function(listener){ | |
listener.call(null,key,val); | |
}); | |
}; | |
/** | |
* Sample View Constructor | |
* @param {Object} model - model object to observe | |
*/ | |
var View = function(model){ | |
this.model = model; | |
this.model.subscribe(this.listener); | |
}; | |
/** | |
* Listener fn that will receive model changes | |
* @param {String} key - name of the property that changed | |
* @param val - new value of the property | |
*/ | |
View.prototype.listener = function(key,val){ | |
console.log('Model property:', key, ' changed value to:', val); | |
}; | |
// Code to Test Observer Pattern | |
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