Custom event in JavaScript like onReadyEvent() -


i need similar functionality own events, such hangout api (and many other apis).

for example, there event: onapiready, invoked when api initialized.

i found great tutorial -> http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/ not know how let create , recall of events spinning each object.

regards.

javascript solution

you have paste following code before script file:

function eventtarget(){     this._listeners = {}; }  eventtarget.prototype = {      constructor: eventtarget,      addlistener: function(type, listener){         if (typeof this._listeners[type] == "undefined"){             this._listeners[type] = [];         }          this._listeners[type].push(listener);     },      fire: function(event){         if (typeof event == "string"){             event = { type: event };         }         if (!event.target){             event.target = this;         }          if (!event.type){  //falsy             throw new error("event object missing 'type' property.");         }          if (this._listeners[event.type] instanceof array){             var listeners = this._listeners[event.type];             (var i=0, len=listeners.length; < len; i++){                 listeners[i].call(this, event);             }         }     },      removelistener: function(type, listener){         if (this._listeners[type] instanceof array){             var listeners = this._listeners[type];             (var i=0, len=listeners.length; < len; i++){                 if (listeners[i] === listener){                     listeners.splice(i, 1);                     break;                 }             }         }     } }; 

then, include

var target = new eventtarget(); function handleevent(event){     alert("api ready ;)"); }; target.addlistener("onapiready", handleevent); 

at top of script.

and then, put following code @ end of api or when initializing it.

target.fire("onapiready"); 

jsfiddle:http://jsfiddle.net/8nyfk/5/. (in demo, i've used settimeout emulate script loading)


Comments

Popular posts from this blog

php - Magento - Deleted Base url key -

java - WrongTypeOfReturnValue exception thrown when unit testing using mockito -

javascript - Tooltipster plugin not firing jquery function when button or any click even occur -