Advertisement
Guest User

Untitled

a guest
Apr 19th, 2015
173
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.56 KB | None | 0 0
  1. ko.observable.fn.virtual = function (override, opts) {
  2. /// <summary>
  3. /// Allow a local observable to be overridden by another observable.
  4. /// </summary>
  5. /// <param name="override" type="Object">
  6. /// The overriding observable, or if the "name" option is present, an object which contains the
  7. /// overriding observable.
  8. /// </param>
  9. /// <param name="opts" type="Object">
  10. /// Options:
  11. /// - useLocalValue (default: false):
  12. /// If true, then the current value of the local observable being overridden is bound to the
  13. /// overriding observable before being returned.
  14. /// - passthrough (default: false):
  15. /// If true, then the local observable is not overridden. Instead, any change to the local
  16. /// observable is passed along to the overriding observable.
  17. /// - name (default: null):
  18. /// If the "override" parameter is not the overriding observable, but is actually an object
  19. /// which contains the overriding observable, then the "name" option represents the property
  20. /// name of the overriding observable within the "override" object
  21. /// (e.g. ko.unwrap(override)[opts.name] would be the overriding observable).
  22. /// </param>
  23. /// <returns type="Object">
  24. /// An observable.
  25. /// </returns>
  26. var self = this,
  27. value = this(),
  28. resultObservable = null,
  29. overridingObservable = null,
  30. options = (opts !== null && typeof opts === 'object') ? opts : {},
  31. settings = {
  32. useLocalValue: (!!options.useLocalValue),
  33. passthrough: (!!options.passthrough),
  34. name: (!!options.name) ? options.name : null
  35. };
  36. if (override && (typeof override === 'object' || ko.isObservable(override))) {
  37. if (settings.name) {
  38. var overrideContainer = ko.unwrap(override);
  39. overridingObservable = ko.isObservable(overrideContainer[settings.name]) ? overrideContainer[settings.name] : null;
  40. } else {
  41. overridingObservable = ko.isObservable(override) ? override : null;
  42. }
  43. }
  44. if (ko.isObservable(overridingObservable)) {
  45. if (settings.useLocalValue) {
  46. overridingObservable(value);
  47. }
  48. if (settings.passthrough) {
  49. this.passthrough = overridingObservable;
  50. this.subscribe(function (newValue) {
  51. self.passthrough(newValue);
  52. });
  53. resultObservable = this;
  54. } else {
  55. resultObservable = overridingObservable;
  56. }
  57. } else {
  58. resultObservable = this;
  59. }
  60. return resultObservable;
  61. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement