Skip to content

Commit

Permalink
Merge pull request #34 from canjs/33-dont-call-value-function-twice
Browse files Browse the repository at this point in the history
Don't call value function twice when observing
  • Loading branch information
imaustink committed Nov 2, 2017
2 parents c59fadd + 7371ae7 commit f0f2c5c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 7 deletions.
12 changes: 5 additions & 7 deletions can-globals-proto.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,12 @@

var canReflect = require('can-reflect');

function dispatch(key, value) {
function dispatch(key) {
// jshint -W040
var handlers = this.eventHandlers[key];
if (handlers) {
var handlersCopy = handlers.slice();
if (typeof value === 'function') {
value = value();
}
var value = this.getKeyValue(key);
for (var i = 0; i < handlersCopy.length; i++) {
handlersCopy[i](value);
}
Expand Down Expand Up @@ -255,7 +253,7 @@ Globals.prototype.deleteKeyValue = function (key) {
if (property !== undefined) {
property.value = property.default;
property.cachedValue = undefined;
dispatch.call(this, key, property.value);
dispatch.call(this, key);
}
return this;
};
Expand Down Expand Up @@ -294,7 +292,7 @@ Globals.prototype.setKeyValue = function (key, value) {
var property = this.properties[key];
property.value = value;
property.cachedValue = undefined;
dispatch.call(this, key, value);
dispatch.call(this, key);
return this;
};

Expand Down Expand Up @@ -322,7 +320,7 @@ Globals.prototype.reset = function () {
if (this.properties.hasOwnProperty(key)) {
this.properties[key].value = this.properties[key].default;
this.properties[key].cachedValue = undefined;
dispatch.call(this, key, this.getKeyValue(key));
dispatch.call(this, key);
}
}
return this;
Expand Down
10 changes: 10 additions & 0 deletions can-globals-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -265,3 +265,13 @@ QUnit.test('onKeyValue should dispatch the resolved value (#29)', function(){
});
globals.offKeyValue('foo');
});

QUnit.test('onKeyValue should not trigger multiple calls of the value function (#33)', function(){
var globals = new Globals();
var baz = spy('baz');
globals.define('foo', 'bar');
globals.onKeyValue('foo', function(){});
globals.setKeyValue('foo', baz);
globals.getKeyValue('foo');
equal(baz.callCount, 1);
});

0 comments on commit f0f2c5c

Please sign in to comment.