I'm using KnockoutJS version 2.0.0
If I'm looping through all properties of an object, how can I test whether each property is a ko.observable
? Here's what I've tried so far:
var vm = { prop: ko.observable(''), arr: ko.observableArray([]), func: ko.computed(function(){ return this.prop + " computed"; }, vm) }; for (var key in vm) { console.log(key, vm[key].constructor === ko.observable, vm[key] instanceof ko.observable); }
But so far everything is false.
Observable arrays combine the power of Knockout. js' observables with native JavaScript arrays. Like native arrays, they contain lists of items that you can manipulate. But since they're observable, Knockout. js automatically updates any associated HTML elements whenever items are added or removed.
To determine if the object is a foreign observable, you can look for a Symbol. observable property. If the property is present and is a function, you can obtain an RxJS Observable from the foreign observable by passing the value returned by calling the object's Symbol.
To create an observable, assign the ko. observable function to the variable. A default value can be specified in the constructor of the call. Knockout then converts your variable into a function and tracks when the value changes, in order to notify the UI elements associated with the variable.
Knockout includes a function called ko.isObservable()
. You can call it like ko.isObservable(vm[key])
.
Update from comment:
Here is a function to determine if something is a computed observable:
ko.isComputed = function (instance) { if ((instance === null) || (instance === undefined) || (instance.__ko_proto__ === undefined)) return false; if (instance.__ko_proto__ === ko.dependentObservable) return true; return ko.isComputed(instance.__ko_proto__); // Walk the prototype chain };
UPDATE: If you are using KO 2.1+ - then you can use ko.isComputed
directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With