Created
June 2, 2013 19:33
-
-
Save vintharas/5694625 to your computer and use it in GitHub Desktop.
Subscribers to knockout observables are notified as soon as the observable changes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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