user2630764
user2630764

Reputation: 622

Difference between myObservableArray.length and myObservableArray().length

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

Answers (1)

Jeroen
Jeroen

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:

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:

  • Use "self.myObservableArray" as a pointer/reference to the property itself;
  • Use "self.myObservableArray()" as a "getter" for the property (to "get" the value: an array);
  • Use "self.myObservableArray(["new item"])" as a "setter" for the property (to "set" a whole new value -new array- to the property).

Upvotes: 2

Related Questions