如何在EaselJS对象中删除事件侦听器

时间:2013-07-15 03:53:12

标签: javascript events easeljs

我使用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");
            }
        }

1 个答案:

答案 0 :(得分: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);
    }
}