Skip to content

Instantly share code, notes, and snippets.

@Vintharas
Created June 2, 2013 19:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Vintharas/5694625 to your computer and use it in GitHub Desktop.
Save Vintharas/5694625 to your computer and use it in GitHub Desktop.
Subscribers to knockout observables are notified as soon as the observable changes
// src/subscribables/subscribable.js
"notifySubscribers": function (valueToNotify, event) {
event = event || defaultEvent;
if (this._subscriptions[event]) {
ko.dependencyDetection.ignore(function() {
ko.utils.arrayForEach(this._subscriptions[event].slice(0), function (subscription) {
// In case a subscription was disposed during the arrayForEach cycle, check
// for isDisposed on each subscription before invoking its callback
if (subscription && (subscription.isDisposed !== true))
subscription.callback(valueToNotify);
});
}, this);
}
},
// src/subscribables/observable.js
ko.observable = function (initialValue) {
var _latestValue = initialValue;
function observable() {
if (arguments.length > 0) {
// Write
// Ignore writes if the value hasn't changed
if ((!observable['equalityComparer']) || !observable['equalityComparer'](_latestValue, arguments[0])) {
observable.valueWillMutate();
_latestValue = arguments[0];
if (DEBUG) observable._latestValue = _latestValue;
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 _latestValue;
}
}
...
observable.valueHasMutated = function () { observable["notifySubscribers"](_latestValue); }
observable.valueWillMutate = function () { observable["notifySubscribers"](_latestValue, "beforeChange"); }
...
return observable;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment