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

泄露秘密 提交于 2019-12-12 02:58:25

问题


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/


回答1:


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/



来源:https://stackoverflow.com/questions/25748258/update-an-input-boxs-text-on-a-click-inside-the-viewmodel-knockout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!