Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if an object property is ko.observable

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.

like image 445
Adam Rackis Avatar asked Mar 08 '12 21:03

Adam Rackis


People also ask

What is Ko observable ()?

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.

How do you know if a variable is observable?

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.

How do you set a value in Ko observable?

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.


1 Answers

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.

like image 77
RP Niemeyer Avatar answered Sep 29 '22 07:09

RP Niemeyer