Skip to content

Commit

Permalink
Retain encapsulation of _latestValue using ES2015 'Symbol' where avai…
Browse files Browse the repository at this point in the history
…lable
  • Loading branch information
SteveSanderson committed Aug 7, 2015
1 parent 07d73f8 commit ac5f21b
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions src/subscribables/observable.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,27 @@
var shouldUseSymbol = !DEBUG && typeof Symbol === 'function';
var latestValueSymbol = shouldUseSymbol ? Symbol('_latestValue') : '_latestValue';

ko.observable = function (initialValue) {
function observable() {
if (arguments.length > 0) {
// Write

// Ignore writes if the value hasn't changed
if (observable.isDifferent(observable._latestValue, arguments[0])) {
if (observable.isDifferent(observable[latestValueSymbol], arguments[0])) {
observable.valueWillMutate();
observable._latestValue = arguments[0];
observable[latestValueSymbol] = arguments[0];
observable.valueHasMutated();
}
return this; // Permits chained assignments
}
else {
// Read
ko.dependencyDetection.registerDependency(observable); // The caller only needs to be notified of changes if they did a "read" operation
return observable._latestValue;
return observable[latestValueSymbol];
}
}

observable._latestValue = initialValue;
observable[latestValueSymbol] = initialValue;

// Inherit from 'subscribable'
if (ko.utils.canSetPrototype) {
Expand All @@ -31,7 +34,7 @@ ko.observable = function (initialValue) {

// Inherit from 'observable'
ko.utils.setPrototypeOfOrExtend(observable, observableFn);

if (ko.options['deferUpdates']) {
ko.extenders['deferred'](observable, true);
}
Expand All @@ -42,9 +45,9 @@ ko.observable = function (initialValue) {
// Define prototype for observables
var observableFn = {
'equalityComparer': valuesArePrimitiveAndEqual,
peek: function() { return this._latestValue },
valueHasMutated: function () { this['notifySubscribers'](this._latestValue); },
valueWillMutate: function () { this['notifySubscribers'](this._latestValue, 'beforeChange'); }
peek: function() { return this[latestValueSymbol]; },
valueHasMutated: function () { this['notifySubscribers'](this[latestValueSymbol]); },
valueWillMutate: function () { this['notifySubscribers'](this[latestValueSymbol], 'beforeChange'); }
};

// Note that for browsers that don't support proto assignment, the
Expand Down

0 comments on commit ac5f21b

Please sign in to comment.