Created
October 11, 2012 22:56
-
-
Save obenjiro/3876095 to your computer and use it in GitHub Desktop.
Observer Pattern (285 chars)
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
//observer pattern - with comments | |
(function() { | |
this.o_O = function(obj, eventList, i, item) { | |
eventList = []; | |
obj.subscribe = function(event,fn) { | |
eventList.push(event, fn); | |
} | |
obj.unsubscribe = function(fn) { | |
eventList.splice(eventList.indexOf(fn)-1, 2); | |
} | |
obj.unsubscribe_all = function(event) { | |
for(i = 0; item = eventList[i]; i++){ | |
if (item == event) { | |
eventList.splice(i,2); | |
i--; | |
} | |
} | |
} | |
obj.fire = function(event,a,b,c,d,e) { | |
for (i in eventList) { | |
if (eventList[i] == event) { | |
eventList[+i + 1](a, b, c, d, e); | |
} | |
} | |
} | |
} | |
})(); | |
//observer pattern - obfuscated (285 chars) | |
!function(){this.o_O=function(a,b,c,d){b=[],a.subscribe=function(a,c){b.push(a,c)},a.unsubscribe=function(a){b.splice(b.indexOf(a)-1,2)},a.unsubscribe_all=function(a){for(c=0;d=b[c];c++)d==a&&(b.splice(c,2),c--)},a.fire=function(a,d,e,f,g,h){for(c in b)b[c]==a&&b[+c+1](d,e,f,g,h)}}}() | |
//observer pattern - usage | |
var observer = {} | |
o_O(observer); //make observer from from object | |
var mouse_up_handler = function(argument1) { | |
console.log("mouseUp subscription called, argument1 = " + argument1) | |
}; | |
var mouse_down_handler = function(argument1, argument2) { | |
console.log("mouseDown subscription called, argument1 = " + argument1 + ", argument2 = " + argument2) | |
}; | |
observer.subscribe("mouse_up", mouse_up_handler); | |
observer.subscribe("mouse_down", mouse_down_handler); | |
observer.fire("mouse_up"); | |
observer.fire("mouse_up", 1); | |
observer.fire("mouse_down", 2, "someValue"); | |
observer.unsubscribe(mouse_up_handler); | |
observer.unsubscribe_all("mouse_down"); | |
observer.fire("mouse_up"); | |
observer.fire("mouse_down"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment