Reputation: 622
I have started learning knockoutjs from their tutorial site, specifically the bit on observable arrays. I'm practising some of the examples.
I want to ask for a very simple clarification, about this code:
var myObservableArray = ko.observableArray();
// Initially an empty array
myObservableArray.push('Some value');
alert('The length of the array is ' + myObservableArray().length);
In the example above, why is myObservableArray().length
used, instead of myObservableArray.length
, since both of them give the same output?
In any conventional language, if I want to refer an object I would be using myObservableArray.length
, so is there any technical reason behind this?
Upvotes: 0
Views: 68
Reputation: 63800
Your assumption that myObservableArray.length
and myObservableArray().length
give the same output is wrong:
ko.applyBindings({ myObservableArray: ko.observableArray(["A", "B", "C", "D"]) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<p>myObservableArray.length = <span data-bind="text: myObservableArray.length"></span></p>
<p>myObservableArray().length = <span data-bind="text: myObservableArray().length"></span></p>
This is because myObservableArray
will contain the return value of calling the function ko.observableArray
, which is not an array, but an observable.
An observable is a function with various properties, and note:
.length
, you call the length
property that all Functions have;.length
on the result, you call the length
property that Arrays have.Bottom line: the two length
properties are very different things. Almost always will you be interested in the length of your underlying array, which is why you should invoke your observable as a function first to "get" the value.
Here's another way to look at this, specifically in the context of view models. Assume this view model:
var MainViewModel = function() {
var self = this;
self.myObservableArray = ko.observableArray(["A", "B", "C"]);
}
Inside your view model you could consider "myObservableArray
" as a property, to be used in three different ways:
self.myObservableArray
" as a pointer/reference to the property itself;self.myObservableArray()
" as a "getter" for the property (to "get" the value: an array);self.myObservableArray(["new item"])
" as a "setter" for the property (to "set" a whole new value -new array- to the property).Upvotes: 2