UNPKG

2.06 kBJavaScriptView Raw
1/**
2 * @fileoverview Reject calls to removeEventListenter where {once: true} could
3 * be used instead.
4 *
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
9
10"use strict";
11
12// -----------------------------------------------------------------------------
13// Rule Definition
14// -----------------------------------------------------------------------------
15
16module.exports = function(context) {
17
18 // ---------------------------------------------------------------------------
19 // Public
20 // --------------------------------------------------------------------------
21
22 return {
23 "CallExpression": function(node) {
24 let callee = node.callee;
25 if (callee.type !== "MemberExpression" ||
26 callee.property.type !== "Identifier" ||
27 callee.property.name !== "addEventListener" ||
28 node.arguments.length == 4) {
29 return;
30 }
31
32 let listener = node.arguments[1];
33 if (listener.type != "FunctionExpression" || !listener.body ||
34 listener.body.type != "BlockStatement" ||
35 !listener.body.body.length ||
36 listener.body.body[0].type != "ExpressionStatement" ||
37 listener.body.body[0].expression.type != "CallExpression") {
38 return;
39 }
40
41 let call = listener.body.body[0].expression;
42 if (call.callee.type == "MemberExpression" &&
43 call.callee.property.type == "Identifier" &&
44 call.callee.property.name == "removeEventListener" &&
45 ((call.arguments[0].type == "Literal" &&
46 call.arguments[0].value == node.arguments[0].value) ||
47 (call.arguments[0].type == "Identifier" &&
48 call.arguments[0].name == node.arguments[0].name))) {
49 context.report(call,
50 "use {once: true} instead of removeEventListener as " +
51 "the first instruction of the listener");
52 }
53 }
54 };
55};