Question

I need similar functionality to its own events, such as the Hangout API (and probably many other APIs).

For example, is there an event: onApiReady, which is invoked when the API is initialized.

I found a great tutorial -> http://www.nczonline.net/blog/2010/03/09/custom-events-in-javascript/ but do not really know how to let you create and recall of events spinning each object.

Regards.

Was it helpful?

Solution

Javascript Solution

You have to paste the following code before your 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];
            for (var i=0, len=listeners.length; i < len; i++){
                listeners[i].call(this, event);
            }
        }
    },

    removeListener: function(type, listener){
        if (this._listeners[type] instanceof Array){
            var listeners = this._listeners[type];
            for (var i=0, len=listeners.length; i < len; i++){
                if (listeners[i] === listener){
                    listeners.splice(i, 1);
                    break;
                }
            }
        }
    }
};

Then, include this

var target = new EventTarget();
function handleEvent(event){
    alert("API is ready ;)");
};
target.addListener("onApiReady", handleEvent);

at the top of your script.

And then, put the following code at the end of your API or when you are initializing it.

target.fire("onApiReady");

JsFiddle:http://jsfiddle.net/8nYfK/5/. (In my demo, I've used setTimeout to emulate script loading)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top