2017-02-02 14 views
0

ウィンドウロード時やサイズ変更時に何らかの処理を行う機能があります。何かが起こるとすぐに私はwindow.resizeイベントリスナーをもう必要としないので、私はresize event listenerを削除しようとしましたが、うまく動作しません。 div.blubbが一度オレンジ色に変更ウィンドウremove eventListener resize function

Code below is same as in this jsFiddle (you need to resize window so not really possible on stackoverflow code snippet)

blubb = function(element) { 
 
\t this.element = element; 
 
    
 
    this.blubber = function() { 
 
    
 
     document.querySelector('.data').innerHTML = window.innerWidth + 'px'; 
 

 
     if(window.innerWidth < 800) { 
 
      this.element.style.backgroundColor = 'orange'; 
 

 
      // here remove EventListener 
 
      // is not working 
 
      window.removeEventListener('resize', (function() { this.blubber() }).bind(this)); 
 
     } else { 
 
      this.element.style.backgroundColor = 'powderblue'; 
 
     } 
 
    }; 
 

 
    this.blubber(); 
 
    window.addEventListener('resize', (function() { this.blubber() }).bind(this)); 
 
}; 
 

 
blubb(
 
\t document.querySelector('.blubb') 
 
);
.blubb { 
 
    width: 300px; 
 
    height: 300px; 
 
    background-color: powderblue; 
 
}
<h1>Change visible area size and reload</h1> 
 
<p>Should be once above 800px and once below 800px</p> 
 
<div class="data"></div> 
 
<div class="blubb"></div>

もしそうなら、私は私が試したイベントリスナ削除したいと思います:

window.removeEventListener('resize', (function() { this.blubber() }).bind(this)); 

をしかし、私はイベントが削除されていない参照してくださいサイズ変更します。私は間違って何をしていますか?

答えて

2

bind()を使用して追加されたイベントリスナーを削除するには、変数にlistener.bind(this)を保存するだけです。 bind()は呼び出されるたびに新しい参照を作成しているためです。

ですから、このような何か行うことができます:

var myListener = function(event) { 
... 
}; 
var myListenerWithContext = myListener.bind(this); 
element.addEventListener('event', myListenerWithContext); 
element.removeEventListener('event', myListenerWithContext); 
+0

それはワットorks https://jsfiddle.net/22oayaLc/3/、ありがとうございます! – caramba

0

何か

var blubb = function(element) { 
    var evt; 
    this.blubber = function() { 
    // code... 
    if(window.innerWidth < 800) { 
     window.removeEventListener('resize', evt); 
    } 
    }; 

    evt = this.blubber.bind(this); 
    window.addEventListener('resize', evt); 
}; 

このようなデモ、そして追加と削除イベントの両方のために使用し、単に関数を作成し、閉鎖を使いませんここでは実際に https://output.jsbin.com/vuyuvohure

コードhttps://jsbin.com/vuyuvohure/edit?html,js,console

関連する問題