このように追加されたイベントリスナーを削除する方法はありますか?
element.addEventListener(event, function(){/* do work here */}, false);
要素を交換せずに?
このように追加されたイベントリスナーを削除する方法はありますか?
element.addEventListener(event, function(){/* do work here */}, false);
要素を交換せずに?
作成時にイベントハンドラーへの参照を保存しない限り、イベントハンドラーをクリーンに削除する方法はありません。
通常、これらをそのページのメインオブジェクトに追加します。その後、そのオブジェクトを使用した後、繰り返し処理してクリーンに破棄できます。
次のようにイベントリスナーを削除できます。
element.addEventListener("click", function clicked() {
element.removeEventListener("click", clicked, false);
}, false);
要素のすべてのイベントリスナーを削除する最も簡単な方法は、要素をそれ自体に割り当てることouterHTML
です。これは、HTMLパーサーを介してHTMLの文字列表現を送信し、解析されたHTMLを要素に割り当てます。JavaScriptが渡されないため、バインドされたイベントリスナーはありません。
document.getElementById('demo').addEventListener('click', function(){
alert('Clickrd');
this.outerHTML = this.outerHTML;
}, false);
<a id="demo" href="javascript:void(0)">Click Me</a>
1つの注意点は、委任されたイベントリスナー、または子の一連の基準に一致するすべてのイベントを監視する親要素のイベントリスナーです。それを乗り越える唯一の方法は、委任されたイベントリスナーの基準を満たさないように要素を変更することです。
document.body.addEventListener('click', function(e){
if(e.target.id === 'demo') {
alert('Clickrd');
e.target.id = 'omed';
}
}, false);
<a id="demo" href="javascript:void(0)">Click Me</a>
古い質問ですが、ここに解決策があります。
厳密に言えば、関数への参照を保存しない限り、匿名のイベントリスナーを削除することはできません。匿名関数を使用する目的はおそらく新しい変数を作成することではないため、代わりに要素自体に参照を格納できます。
element.addEventListener('click',element.fn=function fn() {
// Event Code
}, false);
後で削除する場合は、次の操作を実行できます。
element.removeEventListener('click',element.fn, false);
3番目のパラメーター(false
)は、イベントリスナーを追加する場合と同じ値である必要があることに注意してください。
しかし、質問自体は別のものを懇願します:なぜですか?
単純な方法.addEventListener()
ではなく、2つの理由があります。.onsomething()
まず、複数のイベントリスナーを追加できます。これは、それらを選択的に削除する場合に問題になります。おそらく、それらに名前を付けることになります。それらをすべて削除したい場合は、@tidy-giantのouterHTML
ソリューションが優れています。
次に、イベントをバブルするのではなく、キャプチャすることを選択するオプションがあります。
どちらの理由も重要でない場合は、より簡単なonsomething
方法を使用することをお勧めします。
上書きelement.addEventListener
して、好きなことをしてみてください。
何かのようなもの:
var orig = element.addEventListener;
element.addEventListener = function (type, listener) {
if (/dontwant/.test(listener.toSource())) { // listener has something i dont want
// do nothing
} else {
orig.apply(this, Array.prototype.slice.apply(arguments));
}
};
ps .:推奨されていませんが、トリックは実行されます(テストされていません)
リテラル関数を使用してイベントハンドラーを割り当てるのは注意が必要です。ノードのクローンを作成してクローンに置き換えることなく、イベントハンドラーを削除する方法がないだけでなく、同じハンドラーを誤って複数回割り当てることもできます。これは、ハンドラーへの参照。2つの関数は、文字が同一であっても、常に2つの異なるオブジェクトとして扱われます。
編集:Manngoがコメントごとに提案したように、.unbind ()はjQuery 3.0で非推奨になり、jQuery 1.7以降で置き換えられるため、.unbind()の代わりに.off( )を使用する必要があります。
これは古い質問であり、jQueryについては言及されていませんが、これは検索用語「jquery removeannonymousイベントハンドラー」の最初の結果であるため、ここに回答を投稿します。
.off()関数を使用して削除してみてください。
$('#button1').click(function() {
alert('This is a test');
});
$('#btnRemoveListener').click(function() {
$('#button1').off('click');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button1">Click me</button>
<hr/>
<button id="btnRemoveListener">Remove listener</button>
ただし、これは、 .addEventListenerではなくjQueryを使用してリスナーを追加した場合にのみ機能します
ここでこれを見つけました。
jQueryを使用している場合はtryoff
メソッド
$("element").off("event");
Jquery .off()メソッドは、.on()でアタッチされたイベントハンドラーを削除します
ECMAScript2015(ES2015、ES6)言語仕様を使用するとnameAndSelfBind
、匿名のコールバックを魔法のように名前付きコールバックに変換し、その本体をそれ自体にバインドするこの関数を使用して、イベントリスナーが内部から自分自身を削除できるようにすることができます。外部スコープから削除する(JSFiddle):
(function()
{
// an optional constant to store references to all named and bound functions:
const arrayOfFormerlyAnonymousFunctions = [],
removeEventListenerAfterDelay = 3000; // an auxiliary variable for setTimeout
// this function both names argument function and makes it self-aware,
// binding it to itself; useful e.g. for event listeners which then will be able
// self-remove from within an anonymous functions they use as callbacks:
function nameAndSelfBind(functionToNameAndSelfBind,
name = 'namedAndBoundFunction', // optional
outerScopeReference) // optional
{
const functionAsObject = {
[name]()
{
return binder(...arguments);
}
},
namedAndBoundFunction = functionAsObject[name];
// if no arbitrary-naming functionality is required, then the constants above are
// not needed, and the following function should be just "var namedAndBoundFunction = ":
var binder = function()
{
return functionToNameAndSelfBind.bind(namedAndBoundFunction, ...arguments)();
}
// this optional functionality allows to assign the function to a outer scope variable
// if can not be done otherwise; useful for example for the ability to remove event
// listeners from the outer scope:
if (typeof outerScopeReference !== 'undefined')
{
if (outerScopeReference instanceof Array)
{
outerScopeReference.push(namedAndBoundFunction);
}
else
{
outerScopeReference = namedAndBoundFunction;
}
}
return namedAndBoundFunction;
}
// removeEventListener callback can not remove the listener if the callback is an anonymous
// function, but thanks to the nameAndSelfBind function it is now possible; this listener
// removes itself right after the first time being triggered:
document.addEventListener("visibilitychange", nameAndSelfBind(function(e)
{
e.target.removeEventListener('visibilitychange', this, false);
console.log('\nEvent listener 1 triggered:', e, '\nthis: ', this,
'\n\nremoveEventListener 1 was called; if "this" value was correct, "'
+ e.type + '"" event will not listened to any more');
}, undefined, arrayOfFormerlyAnonymousFunctions), false);
// to prove that deanonymized functions -- even when they have the same 'namedAndBoundFunction'
// name -- belong to different scopes and hence removing one does not mean removing another,
// a different event listener is added:
document.addEventListener("visibilitychange", nameAndSelfBind(function(e)
{
console.log('\nEvent listener 2 triggered:', e, '\nthis: ', this);
}, undefined, arrayOfFormerlyAnonymousFunctions), false);
// to check that arrayOfFormerlyAnonymousFunctions constant does keep a valid reference to
// formerly anonymous callback function of one of the event listeners, an attempt to remove
// it is made:
setTimeout(function(delay)
{
document.removeEventListener('visibilitychange',
arrayOfFormerlyAnonymousFunctions[arrayOfFormerlyAnonymousFunctions.length - 1],
false);
console.log('\nAfter ' + delay + 'ms, an event listener 2 was removed; if reference in '
+ 'arrayOfFormerlyAnonymousFunctions value was correct, the event will not '
+ 'be listened to any more', arrayOfFormerlyAnonymousFunctions);
}, removeEventListenerAfterDelay, removeEventListenerAfterDelay);
})();
//get Event
let obj = window; //for example
let eventStr= "blur"; //for example
let index= 0; //you can console.log(getEventListeners(obj)[eventStr]) and check index
let e = getEventListeners(obj)[eventStr][index];
//remove this event
obj .removeEventListener(eventStr,e.listener,e.useCapture);
終わり:)私はクローム92でテストし、働いた
customEventのoptionsパラメーターの使用方法
options Optional
An object that specifies characteristics about the event listener. The available options are:
...
**once**
A boolean value indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.
私が作成したカスタム関数の場合、それは非常にうまく機能しました。
const addItemOpenEventListener = (item, openItem) => {
document.addEventListener('order:open', ({detail}) => {
if(detail.id === item.id) {
openItem();
}
}, {once: true})
};
el.addItemOpenEventListener(item, () => dispatch(itemOpen)()));
私のコンソールをチェックしました、それはうまくいったようです(フィードバックはありがたいです!)
以下は私にとって十分にうまくいきました。このコードは、別のイベントがリスナーの要素からの削除をトリガーする場合を処理します。事前に関数を宣言する必要はありません。
myElem.addEventListener("click", myFunc = function() { /*do stuff*/ });
/*things happen*/
myElem.removeEventListener("click", myFunc);