Aaron
Aaron

Reputation: 1052

How do I update a knockoutjs observable array item

I have a view model setup with an observable array of user objects. The add/remove of items are working correctly but how do I update items? I can find the values using the ko indexOf function.

function User( username, date_inactive, date_active ) {
    this.username = username;
    this.date_active = date_active;
    this.date_inactive = date_inactive;
};  

User.prototype.inactivateMe = function() {
    json_responses.push( this );
    $.getJSON( "url" + this.username, function( json ) {
        original = json_response.pop();
        //do update here
    });
};

userModel = [  ], //Where the loaded usernames are stored. 

viewUserModel = {
    users: ko.observableArray(userModel)
    //.......

    //This is how I'm adding users to the array.
addUser: function () {
    $.getJSON( "url", 
    { username: usern }, 
        function( json ) { 
            if( json.STATUS != undefined && json.STATUS == 'success' ) {
                newuser = new User( json.USERNAME, json.DATE_ACTIVE, json.DATE_INACTIVE  );
                viewUserModel.users.push( newuser );            
            }
        }
    });
    }

The values of viewUserModel.users are pushed into the array from a server json reponse.

I want to be able to update the date_active and date_inactive values when the user clicks a button and the server responses with success.

My setup is an adaption from http://net.tutsplus.com/tutorials/javascript-ajax/into-the-ring-with-knockout-js-the-title-fight/

Upvotes: 2

Views: 2352

Answers (1)

Rynan
Rynan

Reputation: 481

An observable array only tracks changes made to the array (such as pushes and pops), not the data itself. You will need to make date-active and date_inactive observables as @Ianzz has specified.

function User( username, date_inactive, date_active ) {
    this.username = username;
    this.date_active = ko.observable(date_active);
    this.date_inactive = ko.observable(date_inactive);
};

Afterwards in your html, do something such as

<div data-bind="foreach: Users">
    <input data-bind="value: date_active"/>
    <input data-bind="value: date_inactive"/>
<div>​

See fiddle for full example.

Upvotes: 2

Related Questions