Brainchild
Brainchild

Reputation: 1874

Knockout observable array not working as expected

I am new to Knockout.js, I have created an observable array and initialized with some data. I am expecting any time the UI is changed (check box or text values) the model should also get updated.

I have also subscribed to the array. but my call back method is never called.

var viewModel = {
    seats:ko.observableArray( [
        { "No": "1", "Booked": "" }, ...
    ] )
};

viewModel.seats.subscribe(
    function(newvalue){
        alert(newvalue);
    }
);

ko.applyBindings( viewModel);

http://jsfiddle.net/2NMJX/

Upvotes: 0

Views: 1645

Answers (1)

Niko
Niko

Reputation: 26730

You've just created an observable array - that means, you get notified whenever the array is updated (an element is added or removed, example: http://jsfiddle.net/2NMJX/1/), but not when the elements themselves are updated. To achieve that, you will need to encapsulate the values in observables:

seats: ko.observableArray( [
    { "No": ko.observable("1"), ...

Then, you're able to subscribe to these observables:

viewModel.seats()[0].No.subscribe( ...

http://jsfiddle.net/2NMJX/2/ (try editing the "1")

Upvotes: 3

Related Questions