Last active
May 9, 2018 06:41
-
-
Save black-black-cat/ca457192850e2303fc7b3284a30f5ccd to your computer and use it in GitHub Desktop.
Publish and subscribe from https://github.com/marcuswestin/store.js/blob/master/plugins/events.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
function PubSub() { | |
return Object.assign(Object.create(_pubSubBase), { | |
_id: 0, | |
_subSignals: {}, | |
_subCallbacks: {} | |
}) | |
} | |
function bind(obj, fn) { | |
return function() { | |
return fn.apply(obj, Array.prototype.slice.call(arguments, 0)) | |
} | |
} | |
function slice(arr, index) { | |
return Array.prototype.slice.call(arr, index || 0) | |
} | |
function each(obj, fn) { | |
pluck(obj, function(val, key) { | |
fn(val, key) | |
return false | |
}) | |
} | |
function map(obj, fn) { | |
var res = (isList(obj) ? [] : {}) | |
pluck(obj, function(v, k) { | |
res[k] = fn(v, k) | |
return false | |
}) | |
return res | |
} | |
function pluck(obj, fn) { | |
if (isList(obj)) { | |
for (var i=0; i<obj.length; i++) { | |
if (fn(obj[i], i)) { | |
return obj[i] | |
} | |
} | |
} else { | |
for (var key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
if (fn(obj[key], key)) { | |
return obj[key] | |
} | |
} | |
} | |
} | |
} | |
function isList(val) { | |
return (val != null && typeof val != 'function' && typeof val.length == 'number') | |
} | |
var _pubSubBase = { | |
constructor: PubSub, | |
_id: null, | |
_subCallbacks: null, | |
_subSignals: null, | |
on: function(signal, callback) { | |
if (!this._subCallbacks[signal]) { | |
this._subCallbacks[signal] = {} | |
} | |
this._id += 1 | |
this._subCallbacks[signal][this._id] = callback | |
this._subSignals[this._id] = signal | |
return this._id | |
}, | |
off: function(subId) { | |
var signal = this._subSignals[subId] | |
delete this._subCallbacks[signal][subId] | |
delete this._subSignals[subId] | |
}, | |
once: function(signal, callback) { | |
var subId = this.on(signal, bind(this, function() { | |
callback.apply(this, arguments) | |
this.off(subId) | |
})) | |
}, | |
fire: function(signal) { | |
var args = slice(arguments, 1) | |
each(this._subCallbacks[signal], function(callback) { | |
callback.apply(this, args) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment