के साथ जोड़ा गया ईवेंट श्रोता को हटाकर जावास्क्रिप्ट में, बाइंड() का उपयोग करके ईवेंट श्रोता के रूप में जोड़े गए फ़ंक्शन को निकालने का सबसे अच्छा तरीका क्या है?बाइबल
उदाहरण
(function(){
// constructor
MyClass = function() {
this.myButton = document.getElementById("myButtonID");
this.myButton.addEventListener("click", this.clickListener.bind(this));
};
MyClass.prototype.clickListener = function(event) {
console.log(this); // must be MyClass
};
// public method
MyClass.prototype.disableButton = function() {
this.myButton.removeEventListener("click", ___________);
};
})();
एक ही रास्ता मैं के बारे में सोच सकते हैं बाँध के साथ जोड़ा हर श्रोता का ट्रैक रखने के लिए है।
(function(){
// constructor
MyClass = function() {
this.myButton = document.getElementById("myButtonID");
this.clickListenerBind = this.clickListener.bind(this);
this.myButton.addEventListener("click", this.clickListenerBind);
};
MyClass.prototype.clickListener = function(event) {
console.log(this); // must be MyClass
};
// public method
MyClass.prototype.disableButton = function() {
this.myButton.removeEventListener("click", this.clickListenerBind);
};
})();
वहाँ यह करने के लिए किसी भी बेहतर तरीके हैं:
इस विधि के साथउदाहरण से ऊपर?
आप (इस) 'this.clickListener = this.clickListener.bind को छोड़कर क्या कर रहे हो,' और 'this.myButton.addEventListener (" क्लिक "यह, .clickListener); ' – Esailija
यह बहुत अच्छा है। यह एक अलग विषय हो सकता है, लेकिन इससे मुझे आश्चर्य हुआ कि मुझे अपनी शेष विधियों के लिए बाध्य करना चाहिए (यह) "इस" कीवर्ड का उपयोग करें, भले ही यह विधि अक्षम अक्षम करे। – takfuruya
मैं हमेशा उन सभी विधियों के लिए कन्स्ट्रक्टर में पहली चीज़ के रूप में ऐसा करता हूं जो कहीं भी पारित होने जा रहे हैं, भले ही मैं उन्हें बाद में हटाने जा रहा हूं। लेकिन सभी विधियों के लिए नहीं, बस जो पास हो जाते हैं। – Esailija