/
no-invalid-remove-event-listener.js
55 lines (50 loc) · 1.45 KB
/
no-invalid-remove-event-listener.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
'use strict';
const {getFunctionHeadLocation} = require('eslint-utils');
const getDocumentationUrl = require('./utils/get-documentation-url.js');
const {methodCallSelector, matches} = require('./selectors/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];
if (['ArrowFunctionExpression', 'FunctionExpression'].includes(listener.type)) {
return {
node: listener,
loc: getFunctionHeadLocation(listener, context.getSourceCode()),
messageId: MESSAGE_ID,
};
}
return {
node: listener.callee.property,
messageId: MESSAGE_ID,
};
},
});
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
create,
meta: {
type: 'problem',
docs: {
description: 'Prevent calling `EventTarget#removeEventListener()` with the result of an expression.',
url: getDocumentationUrl(__filename),
},
schema: [],
messages,
},
};