refactor
refactor

Reputation: 15094

How to use ko.observableArray?

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.

Upvotes: 0

Views: 2950

Answers (3)

mg1075
mg1075

Reputation: 18155

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.

Upvotes: 2

cillierscharl
cillierscharl

Reputation: 7117

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);

Upvotes: 1

Ilya
Ilya

Reputation: 29703

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

Upvotes: 0

Related Questions