第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

刪除通過綁定添加的事件偵聽器

刪除通過綁定添加的事件偵聽器

明月笑刀無情 2019-12-17 14:54:21
在JavaScript中,刪除使用bind()添加為事件偵聽器的函數(shù)的最佳方法是什么?例(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", ___________);    };})();我能想到的唯一方法是跟蹤添加了bind的每個(gè)偵聽器。上面的示例使用此方法:(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);    };})();有沒有更好的方法可以做到這一點(diǎn)?
查看完整描述

3 回答

?
千萬里不及你

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超9個(gè)贊

盡管@machineghost所說的是正確的,但事件的添加和刪除方式相同,但等式中缺少的部分是:


.bind()調(diào)用后會(huì)創(chuàng)建一個(gè)新的函數(shù)引用!


請(qǐng)參見bind()是否會(huì)更改函數(shù)引用?| 如何永久設(shè)置?


因此,要添加或刪除它,請(qǐng)將引用分配給變量:


var x = this.myListener.bind(this);

Toolbox.addListener(window, 'scroll', x);

Toolbox.removeListener(window, 'scroll', x);

這對(duì)我來說是預(yù)期的。


查看完整回答
反對(duì) 回復(fù) 2019-12-17
?
胡說叔叔

TA貢獻(xiàn)1804條經(jīng)驗(yàn) 獲得超8個(gè)贊

對(duì)于那些在將React組件的偵聽器注冊(cè)到Flux存儲(chǔ)中或從Flux存儲(chǔ)中移除React偵聽器時(shí)遇到此問題的人,請(qǐng)將以下行添加到組件的構(gòu)造函數(shù)中:


class App extends React.Component {

  constructor(props){

    super(props);

    // it's a trick! needed in order to overcome the remove event listener

    this.onChange = this.onChange.bind(this);  

  }

  // then as regular...

  componentDidMount (){

    AppStore.addChangeListener(this.onChange);

  }

  

  componentWillUnmount (){

    AppStore.removeChangeListener(this.onChange);

  }


  onChange () {

    let state = AppStore.getState();

    this.setState(state);

  }

  

  render() {

    // ...

  }

  

}


查看完整回答
反對(duì) 回復(fù) 2019-12-17
  • 3 回答
  • 0 關(guān)注
  • 390 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)