簡體   English   中英

有關CPU消耗的JavaScript命名函數和事件處理程序

[英]JavaScript Named functions and Event handlers regarding CPU consumption

按照@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,如何將其最小化? 我讀了一些有關刪除事件處理程序的能力,這是解決方案嗎? 以及如何將該解決方案有效地集成到代碼中?

提前致謝。

(使用“ addEventListener” 編輯此命令是不正確的,但出於歷史的原因我將其保留在這里:)您的“ action1”事件處理程序在每次調用時都會重新綁定“ mousemove”處理程序。 反過來,該處理程序將新的處理程序綁定為“ mouseup”。 不久之后,將有成百上千的冗余處理程序。

因此,課程是:不要將事件處理程序綁定到其他事件處理程序中(除非您確實有充分的理由)。 編輯 —對不起;正如我在上面的寫中所指出的那樣,這都是不正確的。我習慣於使用jQuery綁定處理程序,並且該庫的行為方式也不相同。)

另外:按照您的描述,“ showBox”函數綁定了調用“ actionAlert”方法的結果,該方法沒有返回值。 我認為您想要的是:

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

您不應在每次mousemove上都為mouseup添加事件偵聽器,也不應在每次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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM