Skip to content

Instantly share code, notes, and snippets.

@goliatone
Last active December 27, 2015 06:49
Show Gist options
  • Save goliatone/7284645 to your computer and use it in GitHub Desktop.
Save goliatone/7284645 to your computer and use it in GitHub Desktop.
Tiny event dispatcher using jQuery
(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);
@goliatone
Copy link
Author

//Create model
var M = function(){this.data={}};

M.prototype.set = function(key, value){ this.data[key] = value; return this;};
M.prototype.get = function(key,def){ return this.data[key] || def; };

//GPub will make M observable and bindable
GPub.bindable(M.prototype, 'set', 'get');

var m = new M();

m.set('test', 23).on('change', function(e, p){
    console.log('change: old %s new %s', p.old, p.value);
}).on('change:test', function(e, p){
    console.log('change.test: old %s new %s', p.old, p.value);
}).set('test',44);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment