knockout-es5.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. /**
  2. * @license
  3. * Knockout ES5 plugin - https://github.com/SteveSanderson/knockout-es5
  4. * Copyright (c) Steve Sanderson
  5. * MIT license
  6. */
  7. var OBSERVABLES_PROPERTY = '__knockoutObservables';
  8. var SUBSCRIBABLE_PROPERTY = '__knockoutSubscribable';
  9. // Model tracking
  10. // --------------
  11. //
  12. // This is the central feature of Knockout-ES5. We augment model objects by converting properties
  13. // into ES5 getter/setter pairs that read/write an underlying Knockout observable. This means you can
  14. // use plain JavaScript syntax to read/write the property while still getting the full benefits of
  15. // Knockout's automatic dependency detection and notification triggering.
  16. //
  17. // For comparison, here's Knockout ES3-compatible syntax:
  18. //
  19. // var firstNameLength = myModel.user().firstName().length; // Read
  20. // myModel.user().firstName('Bert'); // Write
  21. //
  22. // ... versus Knockout-ES5 syntax:
  23. //
  24. // var firstNameLength = myModel.user.firstName.length; // Read
  25. // myModel.user.firstName = 'Bert'; // Write
  26. // `ko.track(model)` converts each property on the given model object into a getter/setter pair that
  27. // wraps a Knockout observable. Optionally specify an array of property names to wrap; otherwise we
  28. // wrap all properties. If any of the properties are already observables, we replace them with
  29. // ES5 getter/setter pairs that wrap your original observable instances. In the case of readonly
  30. // ko.computed properties, we simply do not define a setter (so attempted writes will be ignored,
  31. // which is how ES5 readonly properties normally behave).
  32. //
  33. // By design, this does *not* recursively walk child object properties, because making literally
  34. // everything everywhere independently observable is usually unhelpful. When you do want to track
  35. // child object properties independently, define your own class for those child objects and put
  36. // a separate ko.track call into its constructor --- this gives you far more control.
  37. function track(obj, propertyNames) {
  38. if (!obj /*|| typeof obj !== 'object'*/) {
  39. throw new Error('When calling ko.track, you must pass an object as the first parameter.');
  40. }
  41. var ko = this,
  42. allObservablesForObject = getAllObservablesForObject(obj, true);
  43. propertyNames = propertyNames || Object.getOwnPropertyNames(obj);
  44. propertyNames.forEach(function(propertyName) {
  45. // Skip storage properties
  46. if (propertyName === OBSERVABLES_PROPERTY || propertyName === SUBSCRIBABLE_PROPERTY) {
  47. return;
  48. }
  49. // Skip properties that are already tracked
  50. if (propertyName in allObservablesForObject) {
  51. return;
  52. }
  53. var origValue = obj[propertyName],
  54. isArray = origValue instanceof Array,
  55. observable = ko.isObservable(origValue) ? origValue
  56. : isArray ? ko.observableArray(origValue)
  57. : ko.observable(origValue);
  58. Object.defineProperty(obj, propertyName, {
  59. configurable: true,
  60. enumerable: true,
  61. get: observable,
  62. set: ko.isWriteableObservable(observable) ? observable : undefined
  63. });
  64. allObservablesForObject[propertyName] = observable;
  65. if (isArray) {
  66. notifyWhenPresentOrFutureArrayValuesMutate(ko, observable);
  67. }
  68. });
  69. return obj;
  70. }
  71. // Gets or creates the hidden internal key-value collection of observables corresponding to
  72. // properties on the model object.
  73. function getAllObservablesForObject(obj, createIfNotDefined) {
  74. var result = obj[OBSERVABLES_PROPERTY];
  75. if (!result && createIfNotDefined) {
  76. result = {};
  77. Object.defineProperty(obj, OBSERVABLES_PROPERTY, {
  78. value : result
  79. });
  80. }
  81. return result;
  82. }
  83. // Computed properties
  84. // -------------------
  85. //
  86. // The preceding code is already sufficient to upgrade ko.computed model properties to ES5
  87. // getter/setter pairs (or in the case of readonly ko.computed properties, just a getter).
  88. // These then behave like a regular property with a getter function, except they are smarter:
  89. // your evaluator is only invoked when one of its dependencies changes. The result is cached
  90. // and used for all evaluations until the next time a dependency changes).
  91. //
  92. // However, instead of forcing developers to declare a ko.computed property explicitly, it's
  93. // nice to offer a utility function that declares a computed getter directly.
  94. // Implements `ko.defineProperty`
  95. function defineComputedProperty(obj, propertyName, evaluatorOrOptions) {
  96. var ko = this,
  97. computedOptions = { owner: obj, deferEvaluation: true };
  98. if (typeof evaluatorOrOptions === 'function') {
  99. computedOptions.read = evaluatorOrOptions;
  100. } else {
  101. if ('value' in evaluatorOrOptions) {
  102. throw new Error('For ko.defineProperty, you must not specify a "value" for the property. You must provide a "get" function.');
  103. }
  104. if (typeof evaluatorOrOptions.get !== 'function') {
  105. throw new Error('For ko.defineProperty, the third parameter must be either an evaluator function, or an options object containing a function called "get".');
  106. }
  107. computedOptions.read = evaluatorOrOptions.get;
  108. computedOptions.write = evaluatorOrOptions.set;
  109. }
  110. obj[propertyName] = ko.computed(computedOptions);
  111. track.call(ko, obj, [propertyName]);
  112. return obj;
  113. }
  114. // Array handling
  115. // --------------
  116. //
  117. // Arrays are special, because unlike other property types, they have standard mutator functions
  118. // (`push`/`pop`/`splice`/etc.) and it's desirable to trigger a change notification whenever one of
  119. // those mutator functions is invoked.
  120. //
  121. // Traditionally, Knockout handles this by putting special versions of `push`/`pop`/etc. on observable
  122. // arrays that mutate the underlying array and then trigger a notification. That approach doesn't
  123. // work for Knockout-ES5 because properties now return the underlying arrays, so the mutator runs
  124. // in the context of the underlying array, not any particular observable:
  125. //
  126. // // Operates on the underlying array value
  127. // myModel.someCollection.push('New value');
  128. //
  129. // To solve this, Knockout-ES5 detects array values, and modifies them as follows:
  130. // 1. Associates a hidden subscribable with each array instance that it encounters
  131. // 2. Intercepts standard mutators (`push`/`pop`/etc.) and makes them trigger the subscribable
  132. // Then, for model properties whose values are arrays, the property's underlying observable
  133. // subscribes to the array subscribable, so it can trigger a change notification after mutation.
  134. // Given an observable that underlies a model property, watch for any array value that might
  135. // be assigned as the property value, and hook into its change events
  136. function notifyWhenPresentOrFutureArrayValuesMutate(ko, observable) {
  137. var watchingArraySubscription = null;
  138. ko.computed(function () {
  139. // Unsubscribe to any earlier array instance
  140. if (watchingArraySubscription) {
  141. watchingArraySubscription.dispose();
  142. watchingArraySubscription = null;
  143. }
  144. // Subscribe to the new array instance
  145. var newArrayInstance = observable();
  146. if (newArrayInstance instanceof Array) {
  147. watchingArraySubscription = startWatchingArrayInstance(ko, observable, newArrayInstance);
  148. }
  149. });
  150. }
  151. // Listens for array mutations, and when they happen, cause the observable to fire notifications.
  152. // This is used to make model properties of type array fire notifications when the array changes.
  153. // Returns a subscribable that can later be disposed.
  154. function startWatchingArrayInstance(ko, observable, arrayInstance) {
  155. var subscribable = getSubscribableForArray(ko, arrayInstance);
  156. return subscribable.subscribe(observable);
  157. }
  158. // Gets or creates a subscribable that fires after each array mutation
  159. function getSubscribableForArray(ko, arrayInstance) {
  160. var subscribable = arrayInstance[SUBSCRIBABLE_PROPERTY];
  161. if (!subscribable) {
  162. subscribable = new ko.subscribable();
  163. Object.defineProperty(arrayInstance, SUBSCRIBABLE_PROPERTY, {
  164. value : subscribable
  165. });
  166. var notificationPauseSignal = {};
  167. wrapStandardArrayMutators(arrayInstance, subscribable, notificationPauseSignal);
  168. addKnockoutArrayMutators(ko, arrayInstance, subscribable, notificationPauseSignal);
  169. }
  170. return subscribable;
  171. }
  172. // After each array mutation, fires a notification on the given subscribable
  173. function wrapStandardArrayMutators(arrayInstance, subscribable, notificationPauseSignal) {
  174. ['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'].forEach(function(fnName) {
  175. var origMutator = arrayInstance[fnName];
  176. arrayInstance[fnName] = function() {
  177. var result = origMutator.apply(this, arguments);
  178. if (notificationPauseSignal.pause !== true) {
  179. subscribable.notifySubscribers(this);
  180. }
  181. return result;
  182. };
  183. });
  184. }
  185. // Adds Knockout's additional array mutation functions to the array
  186. function addKnockoutArrayMutators(ko, arrayInstance, subscribable, notificationPauseSignal) {
  187. ['remove', 'removeAll', 'destroy', 'destroyAll', 'replace'].forEach(function(fnName) {
  188. // Make it a non-enumerable property for consistency with standard Array functions
  189. Object.defineProperty(arrayInstance, fnName, {
  190. enumerable: false,
  191. value: function() {
  192. var result;
  193. // These additional array mutators are built using the underlying push/pop/etc.
  194. // mutators, which are wrapped to trigger notifications. But we don't want to
  195. // trigger multiple notifications, so pause the push/pop/etc. wrappers and
  196. // delivery only one notification at the end of the process.
  197. notificationPauseSignal.pause = true;
  198. try {
  199. // Creates a temporary observableArray that can perform the operation.
  200. result = ko.observableArray.fn[fnName].apply(ko.observableArray(arrayInstance), arguments);
  201. }
  202. finally {
  203. notificationPauseSignal.pause = false;
  204. }
  205. subscribable.notifySubscribers(arrayInstance);
  206. return result;
  207. }
  208. });
  209. });
  210. }
  211. // Static utility functions
  212. // ------------------------
  213. //
  214. // Since Knockout-ES5 sets up properties that return values, not observables, you can't
  215. // trivially subscribe to the underlying observables (e.g., `someProperty.subscribe(...)`),
  216. // or tell them that object values have mutated, etc. To handle this, we set up some
  217. // extra utility functions that can return or work with the underlying observables.
  218. // Returns the underlying observable associated with a model property (or `null` if the
  219. // model or property doesn't exist, or isn't associated with an observable). This means
  220. // you can subscribe to the property, e.g.:
  221. //
  222. // ko.getObservable(model, 'propertyName')
  223. // .subscribe(function(newValue) { ... });
  224. function getObservable(obj, propertyName) {
  225. if (!obj /*|| typeof obj !== 'object'*/) {
  226. return null;
  227. }
  228. var allObservablesForObject = getAllObservablesForObject(obj, false);
  229. return (allObservablesForObject && allObservablesForObject[propertyName]) || null;
  230. }
  231. // Causes a property's associated observable to fire a change notification. Useful when
  232. // the property value is a complex object and you've modified a child property.
  233. function valueHasMutated(obj, propertyName) {
  234. var observable = getObservable(obj, propertyName);
  235. if (observable) {
  236. observable.valueHasMutated();
  237. }
  238. }
  239. // Extends a Knockout instance with Knockout-ES5 functionality
  240. function attachToKo(ko) {
  241. ko.track = track;
  242. ko.getObservable = getObservable;
  243. ko.valueHasMutated = valueHasMutated;
  244. ko.defineProperty = defineComputedProperty;
  245. }
  246. export default {
  247. attachToKo : attachToKo
  248. };