Created
February 1, 2017 12:47
-
-
Save fatso83/942b09f3ee193a69df5a01448d078110 to your computer and use it in GitHub Desktop.
Observable impl - ripped from riot.js 1.0.4. No dependencies.
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 observable = function(el) { | |
var callbacks = {}, slice = [].slice; | |
el.on = function(events, fn) { | |
if (typeof fn === "function") { | |
events.replace(/[^\s]+/g, function(name, pos) { | |
(callbacks[name] = callbacks[name] || []).push(fn); | |
fn.typed = pos > 0; | |
}); | |
} | |
return el; | |
}; | |
el.off = function(events, fn) { | |
if (events === "*") callbacks = {}; | |
else if (fn) { | |
var arr = callbacks[events]; | |
for (var i = 0, cb; (cb = arr && arr[i]); ++i) { | |
if (cb === fn) { arr.splice(i, 1); i--; } | |
} | |
} else { | |
events.replace(/[^\s]+/g, function(name) { | |
callbacks[name] = []; | |
}); | |
} | |
return el; | |
}; | |
// only single event supported | |
el.one = function(name, fn) { | |
if (fn) fn.one = true; | |
return el.on(name, fn); | |
}; | |
el.trigger = function(name) { | |
var args = slice.call(arguments, 1), | |
fns = callbacks[name] || []; | |
for (var i = 0, fn; (fn = fns[i]); ++i) { | |
if (!fn.busy) { | |
fn.busy = true; | |
fn.apply(el, fn.typed ? [name].concat(args) : args); | |
if (fn.one) { fns.splice(i, 1); i--; } | |
fn.busy = false; | |
} | |
} | |
return el; | |
}; | |
return el; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment