0

我不确定为什么在渲染视图时它会正确添加事件侦听器,但如果我尝试在另一个事件函数中添加一个事件侦听器,它是未定义的并引发错误。我怎样才能让它正确添加事件?

解决方法是添加一个变量来存储鼠标是否按下,但我觉得只是添加和删除事件侦听器看起来很清晰。它还否定了对另一个杂乱变量的需要。

代码:

render: function() {
        //sets up a new Easeljs stage called context
        Canvas.context.addEventListener("stagemousedown", this.handleMouseDown);
        Canvas.context.addEventListener("stagemouseup", this.handleMouseUp);
    },

    handleMouseDown: function() {
        console.log('down');
        Canvas.context.addEventListener("stagemousemove", this.handleMouseMove);
    },

    handleMouseMove: function() {
        console.log('moving');
    },

    handleMouseUp: function() {
        console.log('up');
        Canvas.context.removeEventListener("stagemousemove", this.handleMouseMove);
    }

错误:

Uncaught TypeError: Cannot read property 'handleEvent' of undefined (09:32:29:386 | error, javascript)
at b.dispatchEvent (public_html/js/libs/easeljs-0.6.1.min.js:14:447)
at b._handlePointerMove (public_html/js/libs/easeljs-0.6.1.min.js:88:490)
at b._handleMouseMove (public_html/js/libs/easeljs-0.6.1.min.js:88:69)
at c.mousemove.f (public_html/js/libs/easeljs-0.6.1.min.js:87:34)
4

1 回答 1

1

_.bindAll(this)你需要这样做initialize

initialize: function () {_.bindAll(this);}

您可能还应该将事件绑定代码移动到初始化,因为每个实例只会调用一次,而render可能会重复调用,从而导致重复的事件处理程序绑定。

于 2013-06-21T01:49:00.750 回答