Skip to content

Commit

Permalink
Add unlisten function
Browse files Browse the repository at this point in the history
Keep generated event handlers, attach with WeakMap to host element
Add tests for events

Support multi-dispatch unlisten (must give event name and handler function
name).

Fixes #1639
  • Loading branch information
dfreedm committed Jun 8, 2015
1 parent bd93dd3 commit 4616576
Show file tree
Hide file tree
Showing 7 changed files with 435 additions and 26 deletions.
56 changes: 55 additions & 1 deletion src/standard/events.html
Original file line number Diff line number Diff line change
Expand Up @@ -84,20 +84,74 @@
this._createEventHandler(node, eventName, methodName));
},

_boundListenerKey: function(eventName, methodName) {
return (eventName + ':' + methodName);
},

_recordEventHandler: function(host, eventName, target, methodName, handler) {
var hbl = host.__boundListeners;
if (!hbl) {
hbl = host.__boundListeners = new WeakMap();
}
var bl = hbl.get(target);
if (!bl) {
bl = {};
hbl.set(target, bl);

This comment has been minimized.

Copy link
@danbeam

danbeam Jun 21, 2016

Contributor

FYI: if I'm reading the code correctly, listen() could [semi-validly?] be called with target === null here, which would cause this to throw with

Uncaught TypeError: Invalid value used as weak map key(…)

I'm currently tracking down a typechecking issue and was wondering whether listen/unlisten can truly be called with null as the actual code (^ this) implies they can, whereas the externs disallow null.

/cc @rictic @azakus

}
var key = this._boundListenerKey(eventName, methodName);
bl[key] = handler;
},

_recallEventHandler: function(host, eventName, target, methodName) {
var hbl = host.__boundListeners;
if (!hbl) {
return;
}
var bl = hbl.get(target);
if (!bl) {
return;
}
var key = this._boundListenerKey(eventName, methodName);
return bl[key];
},

_createEventHandler: function(node, eventName, methodName) {
var host = this;
return function(e) {
var handler = function(e) {
if (host[methodName]) {
host[methodName](e, e.detail);
} else {
host._warn(host._logf('_createEventHandler', 'listener method `' +
methodName + '` not defined'));
}
};
this._recordEventHandler(host, eventName, node, methodName, handler);
return handler;
},

/**
* Convenience method to remove an event listener from a given element,
* late bound to a named method on this element.
*
* @method unlisten
* @param {Element} node Element to remove event listener from.
* @param {string} eventName Name of event to stop listening to.
* @param {string} methodName Name of handler method on `this` to not call
anymore.
*/
unlisten: function(node, eventName, methodName) {
var handler = this._recallEventHandler(this, eventName, node, methodName);
if (handler) {
this._unlisten(node, eventName, handler);
}
},

_listen: function(node, eventName, handler) {
node.addEventListener(eventName, handler);
},

_unlisten: function(node, eventName, handler) {
node.removeEventListener(eventName, handler);
}
});

Expand Down
29 changes: 29 additions & 0 deletions src/standard/gestures.html
Original file line number Diff line number Diff line change
Expand Up @@ -224,6 +224,27 @@
}
},

// automate event listener removal for native events
remove: function(node, evType, handler) {
var recognizer = this.gestures[evType];
var deps = recognizer.deps;
var name = recognizer.name;
var gobj = node[GESTURE_KEY];
if (gobj) {
for (var i = 0, dep, gd; i < deps.length; i++) {
dep = deps[i];
gd = gobj[dep];
if (gd && gd[name]) {
gd[name] = (gd[name] || 1) - 1;
if (gd[name] === 0) {
node.removeEventListener(dep, this.handleNative);
}
}
}
}
node.removeEventListener(evType, handler);
},

register: function(recog) {
this.recognizers.push(recog);
for (var i = 0; i < recog.emits.length; i++) {
Expand Down Expand Up @@ -476,6 +497,14 @@
node.addEventListener(eventName, handler);
}
},
// override _unlisten to handle gestures
_unlisten: function(node, eventName, handler) {
if (Gestures.gestures[eventName]) {
Gestures.remove(node, eventName, handler);
} else {
node.removeEventListener(eventName, handler);
}
},
/**
* Override scrolling behavior to all direction, one direction, or none.
*
Expand Down
1 change: 1 addition & 0 deletions test/runner.html
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
'unit/bind.html',
'unit/bind.html?dom=shadow',
'unit/notify-path.html',
'unit/events.html',
'unit/gestures.html',
'unit/utils.html',
'unit/utils-content.html',
Expand Down
95 changes: 95 additions & 0 deletions test/unit/events-elements.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->

<link rel="import" href="../../polymer.html">

<script>
var EventLoggerImpl = {
created: function() {
this._handled = {};
this._warned = [];
this._removed = [];
},
handle: function(e) {
this._handled[e.currentTarget.localName] = e.type;
},
_warn: function(array) {
var hasColor = array[0].indexOf('%c') === 0;
var funIdx = hasColor ? 3 : 2;
var messageIdx = hasColor ? 4 : 3;
if (array[funIdx] === '_createEventHandler') {
this._warned.push(array[messageIdx]);
} else {
Polymer.Base._warn(array);
}
},
_unlisten: function(node, eventName, handler) {
this._removed.push({target: node.localName, event: eventName});
Polymer.Base._unlisten(node, eventName, handler);
}
};
</script>

<dom-module id="x-listeners">
<script>
Polymer({
is: 'x-listeners',
behaviors: [EventLoggerImpl],
listeners: {
foo: 'handle',
bar: 'missing'
},
teardown: function() {
this.unlisten(this, 'foo', 'handle');
this.unlisten(this, 'bar', 'missing');
}
});
</script>
</dom-module>

<dom-module id="x-on">
<template>
<div id="inner" on-foo="handle" on-bar="missing"></div>
</template>
<script>
Polymer({
is: 'x-on',
behaviors: [EventLoggerImpl],
teardown: function() {
this.unlisten(this.$.inner, 'foo', 'handle');
this.unlisten(this.$.inner, 'bar', 'missing');
}
});
</script>
</dom-module>

<dom-module id="x-dynamic">
<template>
<div id="inner"></div>
</template>
<script>
Polymer({
is: 'x-dynamic',
behaviors: [EventLoggerImpl],
setup: function() {
this.listen(this, 'foo', 'handle');
this.listen(this.$.inner, 'foo', 'handle');
this.listen(this, 'bar', 'missing');
this.listen(this.$.inner, 'bar', 'missing');
},
teardown: function() {
this.unlisten(this, 'foo', 'handle');
this.unlisten(this.$.inner, 'foo', 'handle');
this.unlisten(this, 'bar', 'missing');
this.unlisten(this.$.inner, 'bar', 'missing');
}
});
</script>
</dom-module>
148 changes: 148 additions & 0 deletions test/unit/events.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
<!DOCTYPE html>
<!--
@license
Copyright (c) 2015 The Polymer Project Authors. All rights reserved.
This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt
The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt
The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt
Code distributed by Google as part of the polymer project is also
subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt
-->
<html>
<head>
<meta charset="UTF-8">

<script src="../../../webcomponentsjs/webcomponents-lite.js"></script>
<script src="../../../web-component-tester/browser.js"></script>

<link rel="import" href="../../polymer.html">
<link rel="import" href="events-elements.html">
</head>
<body>

<script>
suite('Event Listeners', function() {
var el;

suite('listeners block', function() {
suiteSetup(function() {
el = document.createElement('x-listeners');
document.body.appendChild(el);
});

suiteTeardown(function() {
document.body.removeChild(el);
});

test('setup', function() {
var boundListeners = el.__boundListeners;
assert(boundListeners, 'listeners are bound');
var map = boundListeners.get(el);
assert(map, 'events have handlers');
Object.keys(el.listeners).forEach(function(l) {
var key = Polymer.Base._boundListenerKey(l, el.listeners[l]);
assert(map[key], 'listener is in event map');
});
});

test('fire', function() {
el.fire('foo');
assert.equal(el._handled[el.localName], 'foo');
el.fire('bar');
assert.equal(el._warned.length, 1);
assert.equal(el._warned[0], 'listener method `missing` not defined');
});

test('teardown', function() {
el.teardown();
assert.deepEqual(el._removed[0], {target: el.localName, event: 'foo'});
assert.deepEqual(el._removed[1], {target: el.localName, event: 'bar'});
});
});

suite('on-*', function() {

suiteSetup(function() {
el = document.createElement('x-on');
document.body.appendChild(el);
});

suiteTeardown(function() {
document.body.removeChild(el);
});

test('setup', function() {
var boundListeners = el.__boundListeners;
assert(boundListeners, 'listeners are bound');
var map = boundListeners.get(el.$.inner);
assert(map, 'events have handlers');
assert(el._notes[0].events.length, 2);

This comment has been minimized.

Copy link
@leodido

leodido Jun 9, 2016

Ehi @azakus, I think you intended assert.equal here.
It always passes because assert(el._notes[0].events.length) happens to be always true (being always greater than 0, 2 precisely).

el._notes[0].events.forEach(function(l) {
var key = Polymer.Base._boundListenerKey(l.name, l.value);
assert(map[key], 'listener is in event map');
});
});

test('fire', function() {
var options = {node: el.$.inner};
el.fire('foo', {}, options);
assert.equal(el._handled.div, 'foo');
assert(!el._handled[el.localName]);
el.fire('bar', {}, options);
assert.equal(el._warned.length, 1);
assert.equal(el._warned[0], 'listener method `missing` not defined');
});

test('teardown', function() {
el.teardown();
assert.deepEqual(el._removed[0], {target: 'div', event: 'foo'});
assert.deepEqual(el._removed[1], {target: 'div', event: 'bar'});
});
});

suite('dynamic', function() {

suiteSetup(function() {
el = document.createElement('x-dynamic');
document.body.appendChild(el);
});

suiteTeardown(function() {
document.body.removeChild(el);
});

test('setup', function() {
assert(!el.__boundListeners, 'listeners are not bound');
el.setup();
var boundListeners = el.__boundListeners;
assert(boundListeners, 'listeners are bound');
var outerMap = boundListeners.get(el);
assert(outerMap, 'element events have handlers');
var innerMap = boundListeners.get(el.$.inner);
assert(innerMap, 'inner div events have handlers');
});

test('fire', function() {
var options = {node: el.$.inner};
el.fire('foo', {}, options);
assert.equal(el._handled.div, 'foo', 'inner handler');
assert.equal(el._handled[el.localName], 'foo', 'outer handler');
el.fire('bar', {}, options);
assert.equal(el._warned.length, 2);
assert.equal(el._warned[0], 'listener method `missing` not defined');
assert.equal(el._warned[1], 'listener method `missing` not defined');
});

test('teardown', function() {
el.teardown();
assert.deepEqual(el._removed[0], {target: el.localName, event: 'foo'});
assert.deepEqual(el._removed[1], {target: 'div', event: 'foo'});
assert.deepEqual(el._removed[2], {target: el.localName, event: 'bar'});
assert.deepEqual(el._removed[3], {target: 'div', event: 'bar'});
});
});
});
</script>

</body>
</html>
15 changes: 15 additions & 0 deletions test/unit/gestures-elements.html
Original file line number Diff line number Diff line change
Expand Up @@ -70,3 +70,18 @@
});
</script>
</dom-module>

<dom-module id="x-dynamic">
<script>
Polymer({
is: 'x-dynamic',
handler: function(){},
setup: function() {
this.listen(this, 'tap', 'handler');
},
teardown: function() {
this.unlisten(this, 'tap', 'handler');
}
});
</script>
</dom-module>
Loading

0 comments on commit 4616576

Please sign in to comment.