Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is use of of ko.observable

Tags:

knockout.js

Hi I'm very new to knockout js.
Please anyone tell me the difference between

{ id: 1, Name: "Nokia", Price: 3000 }
{ id: ko.observable(1), Name: ko.observable("Nokia"), Price: ko.observable(3000) 

Thanks

like image 459
user3474086 Avatar asked Dec 15 '22 00:12

user3474086


2 Answers

KO is that it updates your UI automatically when the view model changes. How can KO know when parts of your view model change? Answer: you need to declare your model properties as observables, because these are special JavaScript objects that can notify subscribers about changes, and can automatically detect dependencies.

It's pretty simple. Just refer the help documentation for knockout.js

http://knockoutjs.com/documentation/observables.html

Hope it helped

like image 113
pj013 Avatar answered Feb 04 '23 22:02

pj013


The documentation and its tutorial are indeed great.

Briefly: ko.observable returns a getter/setter function. Your first object is just plain values.

In the first case you can do obj.Price = obj.Price + 1000.

In the second you should do obj.Price(obj.Price() + 1000).

The benefits of the function approach is that it enables automatic change tracking.

If this is not clear enough, please look at KO's documentation, it's very good.

like image 32
jods Avatar answered Feb 04 '23 22:02

jods