bindable none DOM objects [ 687 views ]
Goal: to build an effective handshake mechanism between objects
In jQuery we have the very useful bind/trigger logic. I want to use some similar on my objects.
What I will do
I will extend the Object class with 3 methods, like _bind, _unbind, _trigger
_bind: to attach a function to my object
_unbind: to detach a function from my object
_trigger: call all attached functions
First of all I need an Array to store the attached functions. This is the first extend of Object class:
Object.defineProperty(Object.prototype, "__bound", { writable: true }); Object.defineProperty(Object.prototype, "bound", { get: function() { this.__bound = this.__bound || []; return this.__bound; } });
_bind method
I want to use with this form obj._bind('event.namespace', function(){alert('triggered')});
TypeExtend(Object, '_bind', function(evt, func) { var evts = evt.split('.'), obj = {namespace: (evts[1] && evts[1]), event: evts[0], f:func} this.bound.push(obj); return this; });
_unbind method
unbind all attached functions obj._unbind();
unbind by namespace obj._unbind('.namespace');
unbind by event name obj._unbind('event');
TypeExtend(Object, '_unbind', function(evt) { if(!this.__bound){return false;} if(!evt){ this.__bound = []; delete this.__bound; } else{ var evts = evt.split('.'); for(var i in this.__bound){ if((evts[1] && this.__bound[i].namespace == evts[1]) || this.__bound[i].event == evts[0]){ delete this.__bound[i]; } } } this.__bound.shrink(); // drop all undefined items return this; });
_trigger method
using obj._trigger('event');
TypeExtend(Object, '_trigger', function(evt) { if(!this.__bound){return false;} for(var i in this.__bound){ if(this.__bound[i].event == evt){ var a = arguments; this.__bound[i].f && (this.__bound[i].f)(a[1],a[2],a[3],a[4],a[5],a[6],a[7],a[8],a[8],a[10]); } } return this; });
use like this
var f = {}; // new Object(); f._bind('evt1.nspc', function(){console.log('first one');}); // a f._bind('evt2.nspc', function(){console.log('second one');}); // b f._bind('evt1.nspc2', function(){console.log('third one');}); // c f._trigger('evt1'); f._trigger('evt2'); f._unbind('.nspc'); // delete a and b f._trigger('evt1'); f._trigger('evt2'); // b is deleted (do nothing) /* first one third one second one third one */
Bindable none DOM objects? Done. ✔