Skip to content

Commit

Permalink
no-invalid-remove-event-listener: Use simple selector (#2113)
Browse files Browse the repository at this point in the history
  • Loading branch information
fisker committed May 16, 2023
1 parent 95e551d commit 808ec47
Showing 1 changed file with 24 additions and 18 deletions.
42 changes: 24 additions & 18 deletions rules/no-invalid-remove-event-listener.js
Original file line number Diff line number Diff line change
@@ -1,30 +1,37 @@
'use strict';
const {getFunctionHeadLocation} = require('@eslint-community/eslint-utils');
const getDocumentationUrl = require('./utils/get-documentation-url.js');
const {methodCallSelector, matches} = require('./selectors/index.js');
const {isMethodCall} = require('./ast/index.js');

const MESSAGE_ID = 'no-invalid-remove-event-listener';
const messages = {
[MESSAGE_ID]: 'The listener argument should be a function reference.',
};

const removeEventListenerSelector = [
methodCallSelector({
method: 'removeEventListener',
minimumArguments: 2,
}),
'[arguments.0.type!="SpreadElement"]',
matches([
'[arguments.1.type="FunctionExpression"]',
'[arguments.1.type="ArrowFunctionExpression"]',
methodCallSelector({method: 'bind', path: 'arguments.1'}),
]),
].join('');

/** @param {import('eslint').Rule.RuleContext} context */
const create = context => ({
[removeEventListenerSelector](node) {
const listener = node.arguments[1];
CallExpression(callExpression) {
if (!(
isMethodCall(callExpression, {
method: 'removeEventListener',
minimumArguments: 2,
optionalCall: false,
optionalMember: false,
})
&& callExpression.arguments[0].type !== 'SpreadElement'
&& (
callExpression.arguments[1].type === 'FunctionExpression'
|| callExpression.arguments[1].type === 'ArrowFunctionExpression'
|| isMethodCall(callExpression.arguments[1], {
method: 'bind',
optionalCall: false,
optionalMember: false,
})
)
)) {
return;
}

const [, listener] = callExpression.arguments;
if (['ArrowFunctionExpression', 'FunctionExpression'].includes(listener.type)) {
return {
node: listener,
Expand All @@ -47,7 +54,6 @@ module.exports = {
type: 'problem',
docs: {
description: 'Prevent calling `EventTarget#removeEventListener()` with the result of an expression.',
url: getDocumentationUrl(__filename),
},
messages,
},
Expand Down

0 comments on commit 808ec47

Please sign in to comment.