3

Creating a wrapper for video element.

function YMplayer() {
    this.video = document.getElementById("video"); /* video object */
    this.addEvents();
}

YMplayer.prototype.addEvents = function () {
    var obj = this.video;
    var events = ["load","click"];

    if (obj) {
        if (obj.addEventListener) {
            for (var i in events) {
                obj.addEventListener(i, this.dispatch(i), false);
            }
        } else if (obj.attachEvent) {
            for (var j in events) {
                obj.attachEvent("on" + j, this.dispatch(j));
            }
        }
    }

};

/* Method to dispatch the events */

YMplayer.prototype.dispatch = function (evt) {
    var evtt = document.createEvent("Events");
    evtt.initEvent(evt, true, false);
    document.dispatchEvent(evtt); /* working fine */
};

var YP = new YMplayer();

but i want to dispatch events from the above YMplayer object.

need a workaround for access addeventlistener for the instance of YMplayer. something like

YP.addEventListener("load",callback);
balaji g
  • 153
  • 2
  • 10
  • I've found couple helpful answers here: http://stackoverflow.com/questions/6635138/is-it-possible-to-dispatch-events-on-regular-objects-not-dom-ones/6635854#6635854 – ryaz Sep 01 '16 at 21:40

1 Answers1

6

You can't use Javascript events on objects, only on elements.

A solution would be to manually implement a simple 'events system', for example using an .on method (similar to jQuery) and storing the function that gets passed to it in your object, and then call that function when you need to fire the 'event'.

Example:

object.prototype.onEvent = function(handler) {
    this.eventHandler = handler;
};

// To bind the event:
instance.onEvent(function(event){
    console.log(event);
});

// When it's time to fire the event, in your object:
this.eventHandler(eventData);

Note: written from scratch and not tested, but I implemented something similar not too long ago and the basic idea works pretty well.

I hope my answer helps.

Wouter
  • 756
  • 3
  • 11