From fe83d1b32c1c69134c6221b39951d784a00bdbd4 Mon Sep 17 00:00:00 2001 From: ahocevar Date: Thu, 29 Aug 2019 22:35:32 +0200 Subject: [PATCH] Only bind listeners when necessary --- src/ol/events.js | 21 +++++++++++++-------- test/spec/ol/events.test.js | 24 ++++++++++++------------ 2 files changed, 25 insertions(+), 20 deletions(-) diff --git a/src/ol/events.js b/src/ol/events.js index 200b048058..02a9b6a224 100644 --- a/src/ol/events.js +++ b/src/ol/events.js @@ -32,14 +32,19 @@ import {clear} from './obj.js'; * @return {ListenerFunction} Bound listener. */ export function bindListener(listenerObj) { - const boundListener = function(evt) { - const listener = listenerObj.listener; - const bindTo = listenerObj.bindTo || listenerObj.target; - if (listenerObj.callOnce) { - unlistenByKey(listenerObj); - } - return listener.call(bindTo, evt); - }; + let boundListener; + if (listenerObj.bindTo || listenerObj.callOnce) { + boundListener = function(evt) { + const listener = listenerObj.listener; + const bindTo = listenerObj.bindTo || listenerObj.target; + if (listenerObj.callOnce) { + unlistenByKey(listenerObj); + } + return listener.call(bindTo, evt); + }; + } else { + boundListener = listenerObj.listener; + } listenerObj.boundListener = boundListener; return boundListener; } diff --git a/test/spec/ol/events.test.js b/test/spec/ol/events.test.js index 2c56d0de75..5430e72956 100644 --- a/test/spec/ol/events.test.js +++ b/test/spec/ol/events.test.js @@ -24,15 +24,14 @@ describe('ol.events', function() { boundListener(); expect(listenerObj.listener.thisValues[0]).to.equal(listenerObj.bindTo); }); - it('binds to the target when bindTo is not provided', function() { - const listenerObj = { - listener: sinon.spy(), - target: {id: 1} - }; - const boundListener = bindListener(listenerObj); - expect(listenerObj.boundListener).to.equal(boundListener); - boundListener(); - expect(listenerObj.listener.thisValues[0]).to.equal(listenerObj.target); + it('binds to the target when bindTo is not provided', function(done) { + const target = new EventTarget(); + const listenerObj = listen(target, 'foo', function() { + expect(this).to.equal(target); + done(); + }); + expect(listenerObj.boundListener).to.equal(listenerObj.listener); + target.dispatchEvent('foo'); }); it('binds a self-unregistering listener when callOnce is true', function() { const bindTo = {id: 1}; @@ -122,13 +121,14 @@ describe('ol.events', function() { describe('listenOnce()', function() { it('creates a one-off listener', function() { + const target = new EventTarget(); const listener = sinon.spy(); const key = listenOnce(target, 'foo', listener); - expect(add.callCount).to.be(1); expect(key.callOnce).to.be(true); - key.boundListener(); + target.dispatchEvent('foo'); + expect(listener.callCount).to.be(1); + target.dispatchEvent('foo'); expect(listener.callCount).to.be(1); - expect(remove.callCount).to.be(1); }); it('does not add the same listener twice', function() { const listener = function() {};