Question

I have written simple example to learn about how ko.observableArray works.

**HTML**:
Count is : <span data-bind="text anotherObservableArray().length"> </span>

JS:
var anotherObservableArray = ko.observableArray( [
{ name: "A", type: "A" },
{ name: "B", type: "B" },
{ name: "C", type: "C" }
]);

ko.applyBindings(anotherObservableArray);

Here is the link for the example am trying to implement

http://jsfiddle.net/Rama_Kishore/ZPDBv/

I was expecting "Count is: 3" output ,instead it's the output is "Count is:"

Please let me know why the count is not getting displayed.

Thanks.

Was it helpful?

Solution 3

ko.observableArray should be a part of model object.
E.g.

var viewModel = new function()
{
   this.anotherObservableArray = ko.observableArray(...);
}  

or

var viewModel = {
   anotherObservableArray : ko.observableArray(...);
}  

Apply bindings

ko.applyBindings(viewModel);  

JSFiddle DEMO

You can find very good knockout online-tutorial here

OTHER TIPS

Here is a working fork of your fiddle:

http://jsfiddle.net/myjkk/2/

Note how the text binding syntax includes a colon:

<span data-bind="text: anotherObservableArray().length"></span>

Note in the javascript how ko.applyBindings is used. See the knockout documentation for Activating Knockout: http://knockoutjs.com/documentation/observables.html

var vm = {
    anotherObservableArray: ko.observableArray([{
        name: "A",
        type: "A"
    }, {
        name: "B",
        type: "B"
    }, {
        name: "C",
        type: "C"
    }])
};

ko.applyBindings(vm);

Also worth noting is that n your original fiddle, you did not include the knockoutjs library.

Couple of issues:

  • You didnt include Knockout as a library in js fiddle
  • You didn't provide a vm object that wraps your observable array
  • You had a typo in the binding

Fiddle : link

var vm = {
    anotherObservableArray : ko.observableArray( [
       { name: "A", type: "A" },
       { name: "B", type: "B" },
       { name: "C", type: "C" }
    ])
}
 ko.applyBindings(vm);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top