2014-03-05 157 views
0

請看看http://jsbin.com/nubeb/1/edit的JavaScript處理程序移除事件,

(function(){ 
    var func = function(e){ 
    console.log("mouse move"); 
    document.removeEventListener("mousemove",func); 
    }; 
    document.addEventListener("mousemove",func); 
    console.log("working"); 
}()); 

我想知道的是,是否有可能從

document.removeEventListener("mousemove",func); 

替換「功能」到其他一些關鍵詞,我想把它寫類似下面的代碼

(function(){ 
    document.addEventListener("mousemove",function(e){ 
    document.removeEventListener("mousemove",***); 
    }); 
}()); 

回答

2

我們有2個不同的選項,這裏的第一個是使用arguments.callee它會在不久的將來被棄用,使用arguments.callee我們已經獲得的正在執行的當前功能,所以你可以做這樣的事情:

(function(){ 
    document.addEventListener("mousemove",function mylistener(e){ 
     document.removeEventListener("mousemove", arguments.callee); 
    }); 
}()); 

警告:ECMAScript中(ES5)的第五版禁止使用 arguments.callee的()嚴格模式。

閱讀更多信息:arguments.callee

正如你看到的,比在不久的將來得到過時等,不能使用arguments.callee,在strict mode它可以給我們帶來一些麻煩。

我們有一個新的選擇,它可以幫助我們不使用arguments.callee。好吧,讓我們說我們有這樣的函數:

var myfunc = function yourfunc(){ 
    //yourfunc is accessible 
}; 
//but here yourfunc is not accessible 

在這段代碼中,我們只能在函數體中,但出此背景下,我們只有myfunc使用​​。這聽起來像我們有一個私人指針在可訪問的功能範圍內,可以使用,而不是arguments.callee

因此,這是新的替代可以在strict mode也使用,所以在你的代碼,你可以做到這一點,如:

(function(){ 
    document.addEventListener("mousemove",function mylistener(e){ 
     document.removeEventListener("mousemove", mylistener); 
    }); 
}());