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);
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);
Share
Improve this question
asked Nov 3, 2015 at 11:33
balaji gbalaji g
1532 silver badges10 bronze badges
1
- I've found couple helpful answers here: stackoverflow./questions/6635138/… – ryaz Commented Sep 1, 2016 at 21:40
1 Answer
Reset to default 6You 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.