Created
October 28, 2014 04:58
-
-
Save rochnyak-d-i/23229afaaddc3f16e5ee to your computer and use it in GitHub Desktop.
JS шаблон слушатель
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
Event = function() { | |
this._observers = []; | |
} | |
Event.prototype = { | |
raise: function (data) { | |
for (var i in this._observers) { | |
var item = this._observers[i]; | |
item.observer.call(item.context, data); | |
} | |
}, | |
subscribe: function (observer, context) { | |
var ctx = context || null; | |
this._observers.push({ observer: observer, context: ctx }); | |
}, | |
unsubscribe: function (observer, context ) { | |
for (var i in this._observers) { | |
if ( this._observers[i].observer == observer && | |
this._observers[i].context == context | |
) { | |
delete this._observers[i]; | |
} | |
} | |
} | |
} | |
var someEvent = new Event(); | |
someEvent.subscribe(function ( data ) { console.log("wohoooooo " + data ) }); | |
var someObject = { | |
_topSecretInfo: 42, | |
observerFunction: function () { console.log("Top Secret:" + this._topSecretInfo) } | |
} | |
someEvent.subscribe(someObject.observerFunction, someObject); | |
someEvent.raise("yeaah!"); | |
someEvent.raise(); | |
//N2 | |
var publisher = { | |
subscribers: [] | |
, on: function(type, fn, context) { | |
type = type || 'any'; | |
fn = typeof fn === 'function' ? fn : context[fn]; | |
if(typeof this.subscribers[type] === 'undefined') { | |
this.subscribers[type] = []; | |
} | |
this.subscribers[type].push({fn: fn, context: context || this}); | |
} | |
, remove: function(type, fn, context) { | |
this.visitSubscribers('unsubscribe', type, fn, context); | |
} | |
, fire: function(type, publication) { | |
this.visitSubscribers('publish', type, publication); | |
} | |
, visitSubscribers: function(action, type, arg, context) { | |
var | |
pubtype = type || 'any' | |
, subscribers = this.subscribers[pubtype] | |
, i | |
, max = subscribers ? subscribers.length : 0 | |
; | |
for(i = 0; i < max; i += 1) { | |
if(action === 'publish') { | |
subscribers[i].fn.call(subscribers[i].context, arg); | |
} else { | |
if(subscribers[i].fn === arg && subscribers[i].context === context) { | |
subscribers.splice(i, 1); | |
} | |
} | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment