summaryrefslogtreecommitdiff
path: root/chromium/ui/webui/resources/js/web_ui_listener_behavior.js
blob: d7fc56b5fff9ab5536ee2c28bc7a5e2c09310f62 (plain)
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
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
 * @fileoverview Behavior to be used by Polymer elements that want to
 * automatically remove WebUI listeners when detached.
 */

/** @polymerBehavior */
var WebUIListenerBehavior = {
  properties: {
    /**
     * Holds WebUI listeners that need to be removed when this element is
     * destroyed.
     * @private {!Array<!WebUIListener>}
     */
    webUIListeners_: {
      type: Array,
      value: function() { return []; },
    },
  },

  /**
   * Adds a WebUI listener and registers it for automatic removal when this
   * element is detached.
   * Note: Do not use this method if you intend to remove this listener
   * manually (use cr.addWebUIListener directly instead).
   *
   * @param {string} eventName The event to listen to.
   * @param {!Function} callback The callback run when the event is fired.
   */
  addWebUIListener: function(eventName, callback) {
    this.webUIListeners_.push(cr.addWebUIListener(eventName, callback));
  },

  /** @override */
  detached: function() {
    while (this.webUIListeners_.length > 0) {
      cr.removeWebUIListener(this.webUIListeners_.pop());
    }
  },
};