I have created my own addEventListener to work with objects on a canvas, but I am having trouble making my own removeEventListener function.
In my shape constructor, I have this code:
this.addEventListener = function(method, func)
{
if (method == "mouseDown")
{
scene.mouseDownShapes.push({shape:this, func:func})
}
}
this.removeEventListener = function(method, func)
{
if (method == "mouseDown")
{
scene.mouseDownShapes.splice(scene.mouseDownShapes.indexOf({shape:this, func:func}), 1);
}
}
In my mouse down handler, I run through scene.mouseDownShapes and check if they collide with the mouse. If they do, then I call func. The problem here is, "scene.mouseDownShapes.indexOf(...)" returns -1, so it doesn't work. How do I find the index of a raw object in an array?
Object equality with .indexOf()
only works for the same physical object (it does not work for a different object that has the same properties).
Since you don't have a reference to the same physical object that you put in the array, what you can do is to search the array for an object that has the property shape: this
. This involves iterating through the array to find it.
this.removeEventListener = function(method, func) {
if (method == "mouseDown"){
for (var i = 0; i < scene.mouseDownShapes.length) {
if (scene.mouseDownShapes[i].shape === this) {
scene.mouseDownShapes.splice(i, 1);
break;
}
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.