Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- ko.observable.fn.virtual = function (override, opts) {
- /// <summary>
- /// Allow a local observable to be overridden by another observable.
- /// </summary>
- /// <param name="override" type="Object">
- /// The overriding observable, or if the "name" option is present, an object which contains the
- /// overriding observable.
- /// </param>
- /// <param name="opts" type="Object">
- /// Options:
- /// - useLocalValue (default: false):
- /// If true, then the current value of the local observable being overridden is bound to the
- /// overriding observable before being returned.
- /// - passthrough (default: false):
- /// If true, then the local observable is not overridden. Instead, any change to the local
- /// observable is passed along to the overriding observable.
- /// - name (default: null):
- /// If the "override" parameter is not the overriding observable, but is actually an object
- /// which contains the overriding observable, then the "name" option represents the property
- /// name of the overriding observable within the "override" object
- /// (e.g. ko.unwrap(override)[opts.name] would be the overriding observable).
- /// </param>
- /// <returns type="Object">
- /// An observable.
- /// </returns>
- var self = this,
- value = this(),
- resultObservable = null,
- overridingObservable = null,
- options = (opts !== null && typeof opts === 'object') ? opts : {},
- settings = {
- useLocalValue: (!!options.useLocalValue),
- passthrough: (!!options.passthrough),
- name: (!!options.name) ? options.name : null
- };
- if (override && (typeof override === 'object' || ko.isObservable(override))) {
- if (settings.name) {
- var overrideContainer = ko.unwrap(override);
- overridingObservable = ko.isObservable(overrideContainer[settings.name]) ? overrideContainer[settings.name] : null;
- } else {
- overridingObservable = ko.isObservable(override) ? override : null;
- }
- }
- if (ko.isObservable(overridingObservable)) {
- if (settings.useLocalValue) {
- overridingObservable(value);
- }
- if (settings.passthrough) {
- this.passthrough = overridingObservable;
- this.subscribe(function (newValue) {
- self.passthrough(newValue);
- });
- resultObservable = this;
- } else {
- resultObservable = overridingObservable;
- }
- } else {
- resultObservable = this;
- }
- return resultObservable;
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement