Last active
December 27, 2015 06:49
-
-
Save goliatone/7284645 to your computer and use it in GitHub Desktop.
Tiny event dispatcher using jQuery
This file contains hidden or 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(exports, name, $){ | |
var GPub = function(){}; | |
GPub.observable = function(src){ | |
var _o = $({}), _l = {}, obj = src || {}; | |
var _d = function(e){ (e in _l) && (_l[e] -= 1); }; | |
var _a = function(e){ (e in _l) || (_l[e] = 0); _l[e] += 1; }; | |
obj.on = function() { _o.on.apply(_o, arguments); _a(arguments[0]); return this;}; | |
obj.off = function() { _o.off.apply(_o, arguments); _d(arguments[0]); return this;}; | |
obj.emit = function() { _o.trigger.apply(_o, arguments); return this;}; | |
obj.once = function() { _o.one.apply(_o, arguments); return this; }; | |
obj.emits = function(e){ return (e in _l && _l[e] > 0);}; | |
return obj; | |
}; | |
GPub.bindable = function(src, set, get, bind){ | |
if(!('on' in src) || !('emit' in src)) this.observable(src); | |
var _set = src[set], _get = src[get]; | |
var method = (function(key, value){ | |
var old = _get.call(this, key); | |
var out = _set.call(this, key, value); | |
if(this.emits('change')) this.emit('change', {old:old, value:value}); | |
if(this.emits('change:'+key)) this.emit('change:'+key, {old:old, value:value}); | |
return out; | |
}); | |
if(bind) method.bind(src); | |
src[set] = method; | |
return src; | |
}; | |
GPub.delegable = function(src, events){ | |
var event, e; | |
// var _binder = function(handler){reutrn } | |
for(e in events){ | |
event = events[e]; | |
src['on'+event] = (function(handler){ | |
this.on(event, handler); | |
}).bind(src); | |
} | |
}; | |
exports[name] = GPub; | |
})(this, 'GPub', jQuery); |
Author
goliatone
commented
Nov 9, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment