<ul>
Behavioral Pattern
<li>
Oberserver or Pub / Sub
</li>
<li>
Command
</li>
</ul>
JavaScript
// Behavioral design pattern deals with communication between objects
// multiple objects are involved to accomplish a common functionality
// Observer pattern : observers subscribe/unsubscribe to a subject
// Allows a group of objects {observers} to watch over an object { subject}
// and be notified of the chnages.
var Observable = function() {
this.subscribers = [];
};
Observable.prototype = {
subscribe: function(callback) {
this.subscribers.push(callback);
},
unsubscribe: function(callback) {
for (var i = 0, l = this.subscribers.length; i < l; i++) {
if (this.subscribers[i] === callback) {
this.subscribers.splice(i, 1);
return;
}
}
},
publish: function(data) {
// call all subscribers
for (var i = 0, l = this.subscribers.length; i < l; i++) {
this.subscribers[i](data)
}
}
}
var observable = new Observable();
var observer1 = function(data) { console.log(data) };
observable.subscribe(observer1);
observable.publish("hello we called");
observable.unsubscribe(observer1);
observable.publish("hello we called again !" );
// command pattern
// encapsulates calling of methods as an object
function Manager() {
this.items = [];
};
Manager.prototype = {
do:function(name) {
var args = Array.prototype.slice.call(arguments,1)[0];
console.log(args);
var fName = "_"+name;
if (this[fName])
{
this[fName](args);
}
},
_add : function(item) {
this.items.push(item);
console.log("adding item to list");
console.log(this.items)
}
}
var m1 = new Manager();
m1.do("add",1);
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.