开发者

Knockout.js fromJSON not Updating ViewModel

I have the following simple case that I am working with:

<ul data-bind='template: {name : "namesTemplate", data:viewModel}'>
</ul>

<script id='namesTemplate' type='text/html'>
    {{each $data}}
        <li>${ Name }</li>
    {{/each}}
</script>

<span data-bind="click: fire">Click Me</span>

<script type='text/javascript'>

    var viewModel = ko.observableArray([{ "Name": "Tom" },
                                        { "Name": "Pete" },
                                        { "Name": "Dave"}]);

    viewModel.fire = function () {
        $.getJSON("Post", function (result) {
            viewModel = ko.mapping.fromJSON(result);
        });
    }

    ko.applyBindings(viewModel);

</script>

getJSON is getting JSON data from an 开发者_开发问答ASP.NET MVC controller, which looks something like:

[{"Name":"Chris"}]

Upon clicking Click Me the unordered list is not being updated. Where am I going wrong?

Thanks.


Two ideas:

1) Name your properties on your view model:

var viewModel = { employees: ko.observableArray([{ "Name": "Tom" },
                                                 { "Name": "Pete" },
                                                 { "Name": "Dave"}]);
};

2) As you already have data in your view model, maybe you should use ko.mapping.updateFromJS:

viewModel.fire = function () {
    $.getJSON("Post", function (result) {
        ko.mapping.updateFromJS(viewModel.employees, result);
    });
}


Have a look at my example:

http://jsfiddle.net/YhXyL/

var viewModel ={
      names: ko.observableArray([{ "Name": "Tom" },
                                 { "Name": "Pete" },
                                 { "Name": "Dave"}])
};

viewModel.fire = function() {
    this.names([{"Name": "test"}]);
};

ko.applyBindings(viewModel);

And the Html:

<ul data-bind='template: {name : "namesTemplate", foreach:names}'></ul>

<span data-bind="click: fire">Click Me</span>

<script id='namesTemplate' type='text/html'>
    <li data-bind="text: Name"/>
</script>

If you'd like to add the new array you can use push method:

this.names.push([{"Name": "test"}]);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜