JavaScript命名函数和有关CPU消耗的事件处理程序

时间:2012-06-11 15:36:53

标签: javascript javascript-events cpu-usage

将我的代码重新分解为@FlorianMargaine建议(在JavaScript聊天对话中)后,我得到的内容如下所示:

body.addEventListener( 'mousedown', action1);
function action1(){
    //Start selecting event
    body.addEventListener( 'mousemove', selectOver);
}
function selectOver(e){
    //after the user has selected and done a mouse up event show a box:
    body.addEventListener( 'mouseup', showBox );
}
function showBox(e){
    //Show box
    box.addEventListener( 'click', actionAlert('clicked on interface after selected text') );
}
function actionAlert(d){
    alert(d);
}

主要问题是我认为它在途中使用了大量的CPU,我该如何最小化? 我读了一下有关删除事件处理程序的能力,是解决方案吗?以及如何将该解决方案有效地集成到代码中?

提前致谢。

2 个答案:

答案 0 :(得分:3)

编辑这在使用“addEventListener”时是不正确的,但我会把它留在这里作为历史好奇心:)你的“action1”事件处理程序每​​次重新绑定“mousemove”处理程序调用。反过来,该处理程序为“mouseup”绑定一个新的处理程序。过了一会儿,就会有成百上千的冗余处理程序。

所以,教训是:不要在其他事件处理程序中绑定事件处理程序(除非你确实有充分的理由)。 (编辑 - 抱歉;正如我上面所写的那样,有人指出这一切都是不正确的。我习惯用jQuery绑定处理程序,并且该库的行为方式不同。)

另外:你的“showBox”函数,正如所写,绑定调用“actionAlert”方法的结果,该方法没有返回值。我想你想要的是:

box.addEventListener( 'click', function() {
  actionAlert('clicked on interface after selected text');
});

答案 1 :(得分:2)

你不应该在每个mouseup上为mousemove添加一个事件监听器,也不应该每次你mousedown 重新注册你的mousemove而不是:

body.addEventListener( 'mousedown', action1, false);
function action1(){
    //Start selecting event
    body.addEventListener( 'mousemove', selectOver, false);
    body.addEventListener( 'mouseup', showBox, false );
    body.addEventListener( 'mouseup', function(){
      body.removeEventListener( 'mousemove', selectOver, false );
    });
}
function selectOver(e){
    // Not sure what this function is for.
}
function actionAlert(d){
    alert(d);
}

我还根据某些(所有?)版本的Firefox要求将显式第三个参数false添加到addEventListener