2

我使用 CreateJS/EaselJS 创建一个画布示例。我有一个卡片对象(位图对象),并向它添加了一个事件侦听器来处理“mousedown”事件。然后我尝试删除这个事件监听器,但它似乎不起作用。谁能帮我?

toggleDragDrop: function (stage, state) {
            if (state) {
                this.graphicsObj.addEventListener("mousedown", function (evt) {
                    var offset = { x: evt.target.x - evt.stageX, y: evt.target.y - evt.stageY };

                    // add a handler to the event object's onMouseMove callback
                    // this will be active until the user releases the mouse button:
                    evt.addEventListener("mousemove", function (ev) {
                        ev.target.x = ev.stageX + offset.x;
                        ev.target.y = ev.stageY + offset.y;
                        stage.update();
                    });
                });
            }
            else {
                this.graphicsObj.removeEventListener("mousedown");
            }
        }
4

1 回答 1

2

.removeEventListener()需要两个(或三个)参数,而不仅仅是一个。第二个参数是对传入的同一侦听器函数的引用.addEventListener().addEventListener()因此,如果您想稍后将其删除,则不能使用匿名函数表达式。相反,请使用命名函数,以便您可以在两个调用中引用它:

toggleDragDrop: function (stage, state) {
    function downer( evt ) {
        var offset = {
            x: evt.target.x - evt.stageX,
            y: evt.target.y - evt.stageY
        };

        // add a handler to the event object's onMouseMove callback
        // this will be active until the user releases the mouse button
        evt.addEventListener("mousemove", function (ev) {
            ev.target.x = ev.stageX + offset.x;
            ev.target.y = ev.stageY + offset.y;
            stage.update();
        });
    }

    if (state) {
        this.graphicsObj.addEventListener("mousedown", downer);
    }
    else {
        this.graphicsObj.removeEventListener("mousedown", downer);
    }
}
于 2013-07-15T07:32:10.013 回答