Last active
February 11, 2016 16:46
-
-
Save monochromer/13269603e3817dccfcee to your computer and use it in GitHub Desktop.
Шаблон "Наблюдатель (Подписчик-Издатель)"
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
var Observer = (function () { | |
'use strict'; | |
var exports = {}; | |
var events = {}, | |
splitter = /\s+/; | |
var on = function(types, fn, context) { | |
var type; | |
types = types.split(splitter); | |
type = types.pop(); | |
context = context || this; | |
while (type) { | |
events[type] = events[type] || []; | |
events[type].push({ | |
context: context, | |
callback: fn | |
}); | |
type = types.pop(); | |
} | |
return this; | |
}; | |
var off = function(types, fn) { | |
var type, | |
index; | |
types = types.split(splitter); | |
type = types.pop(); | |
while (type && type in events) { | |
index = events[type].indexOf(fn); | |
events[type].splice(index, 1); | |
if(events[type].length === 0) { | |
delete events[type]; | |
} | |
type = types.pop(); | |
} | |
return this; | |
}; | |
var once = function(types, fn, context) { | |
var self = this; | |
function handler() { | |
self.off(types, handler); | |
fn.apply(context, arguments); | |
} | |
this.on(types, handler, context); | |
return this; | |
}; | |
var emit = function(types) { | |
var type, args, e, | |
subscription, | |
len; | |
types = types.split(splitter); | |
type = types.pop(); | |
args = Array.prototype.slice.call(arguments, 1); | |
while(type && (type in events)) { | |
e = events[type]; | |
for (len = e.length; len > 0; len -= 1) { | |
subscription = e[len - 1]; | |
subscription.callback.apply(subscription.context, args); | |
} | |
type = types.pop(); | |
} | |
}; | |
exports.on = on; | |
exports.off = off; | |
exports.once = once; | |
exports.emit = emit; | |
return exports; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment