Skip to content

Instantly share code, notes, and snippets.

@monochromer
Last active February 11, 2016 16:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save monochromer/13269603e3817dccfcee to your computer and use it in GitHub Desktop.
Save monochromer/13269603e3817dccfcee to your computer and use it in GitHub Desktop.
Шаблон "Наблюдатель (Подписчик-Издатель)"
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