Search code examples
knockout.jsknockout-mapping-plugin

Update an Input Box's text on a click inside the viewmodel - knockout


I have a question regarding updating currently bound nested viewmodels and that is related to my last question here.

This is for a test where I added a simple Input box to sample my current problem.

The problem is:

ViewModel is bound inside a template(Don't think the sample should necessarily be) On a button click we want to update the Input Box located inside it, The input box won't be updated, I did getting reports by console and seems the data is changed. What is your idea, Fiddle is located at the bottom of this question.

 <div data-bind="foreach: Groups">

     <input data-bind="value:newText" /> ...

The goal is in the line :

self.newText = 'Added'; // were it doesn't take effect

ViewModel which contains manual mapping:

function groupViewModel(data) {
    var self = this;
    self.newText = ko.observable('');
    ko.mapping.fromJS(data, {}, self);
    self.addPerson = function(personData) {
        // here should be your ajax request, I'll use dummy data again
        self.People.push({Name: "Michael", LastName: "Bay"});
        *self.newText = 'Added';*
        //ko.mapping.fromJS(data, {}, self);
    };    
}
var mapping = {
    "Groups" : {
        'create': function(options) {
            return new groupViewModel(options.data);
        }
    }
};

The whole code is located on fiddle:

http://jsfiddle.net/btbp9o4c/1/


Solution

  • Your error is here:

    self.newText = 'Added';
    

    Needs to be:

    self.newText('Added');
    

    As you are incorrectly reassigning the observable. Here is the updated fiddle:

    http://jsfiddle.net/6L9ozbtp/