所以我正在编写可移动 SVG 对象的实现。 (我确实想自己做这件事,因为我需要一些特殊功能)
对于每个 SVG,我都有一个带有额外数据等的 JS 对象。
在构造函数中,我创建一个 SVG 元素并将其附加到 SVG。
var self; // maybe this is a problem? I need it for prototyping and the whole code is wrapped in a factory function
var Scooter = function(id) {
this.id = id; // this is just n-th instance
this.svgElement = document.createElementNS(SVG_NS, "g");
// doing some extra svg stuff
SVG.appendChild(this.svgElement);
self = this; // need this for the listener
// **1**
}
现在我想添加可拖动功能,因此我仍在构造函数中绑定(bind)事件监听器。 (请参阅上面代码示例中的 **1**
)
$(self.svgElement).on("mousedown", function(e) {
// do sth for making it draggable
console.log(self);
}
好的。现在,如果我创建一个实例,它就可以正常工作。当我添加第二个实例时,一切似乎都很好。我可以移动第二个,就像它应该的那样。但是,如果我再次拖动第一个对象,它将移动第二个(或最后创建的)对象!
每个 SVG 元素都完美显示,我认为每个元素都有自己的处理程序。但是,如果我从第一个对象检查处理程序的闭包变量,self
现在将为我提供对最新对象的引用。
有人可以解释一下为什么会发生这种情况吗?也许建议一个解决方法?
最佳答案
嗯,类似
var Something = (function(){
//constructor
function Something(){
....
}
Something.prototype = {
func1: function() {
},
func_n: function() {
}
};
return something;
})()
没有 self
关于javascript - 关闭事件监听器不适用于多个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31250561/