从json模型中剔除JS更新视图 [英] Knockout JS update view from json model

查看:56
本文介绍了从json模型中剔除JS更新视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请参考此问题,因为它有助于解决我的问题的50%:

Please refer to this question as it helped solving 50% of my issue:

挖空映射读取JSON

另外50%的问题是更新视图,如果两次调用ko.applyBindings(viewModel);,则会出现错误 Uncaught Error:您无法将绑定多次应用于同一元素.

the other 50% of issue is updating view, if you call ko.applyBindings(viewModel); twice, you get an error Uncaught Error: You cannot apply bindings multiple times to the same element.

即使在他们提到的官方淘汰赛网站上,也没有人提出解决方案:

No one online ever proposed a solution to this, even on the official knockout site they mentioned:

// Every time data is received from the server:
ko.mapping.fromJS(data, viewModel);

这也不起作用.任何人都知道每次获取新数据时更新视图的正确方法是什么,知道该视图已经通过ko.applyBindings(viewModel);初始化了吗?

which is not working either. Anyone knows what the proper method is to update my view each time I fetch new data, knowing that the view is already initialized via ko.applyBindings(viewModel);?

HTML:

<select class="input-short artist-list" data-bind="foreach: model">
   <option value="1" selected="selected" data-bind="text: name"></option>                                           
 </select>  

JS

var viewModel = {
        model: ko.observableArray()            
    };


$(window).load(function(){
    fetchArtists();  

  })
function fetchArtists() //this function fetches all artists
{
     // load data
       $.post( "../db/fetch/", { table: "artists"})
          .done(function( data ) {
          //  artists=JSON.parse(data);
          data=JSON.parse(data);//data is array of objects e.g [{name:"xxx"},{name:"yyy"}]   
          artists.model = ko.mapping.fromJS(data);         
          ko.applyBindings(artists);      
          });

}

推荐答案

在剔除中,一次将ViewModel应用于视图(applyBindings).每次与数据绑定绑定的可观察对象都会更新(例如,向它们分配新数据),则将重新渲染视图.您的错误是绑定了一个不可观察的(模型)并在每个函数调用中重新定义artist.model.

In knockout, a ViewModel is applied to the view once (applyBindings). Everytime the observables bind with data-bind are updated (e.g. assigning new data to them), the view is re-rendered. Your mistake is binding a non-observable (model) and re-defining artists.model with every function call.

您应该通过以下方式进行操作:

You should do it the following way:

var viewModel = {
    artists: ko.observableArray()          
};


$(window).load(function(){
    fetchArtists();  
});

function fetchArtists()
{
     // load data
       $.post( "../db/fetch/", { table: "artists"})
          .done(function( data ) {
              viewModel.artists(JSON.parse(data)); // assign new values to artists observable          
       });
}

HTML

<select class="input-short artist-list" data-bind="foreach: artists">
   <option value="1" selected="selected" data-bind="text: name"></option>                                           
</select>

<script>
    ko.applyBindings(viewModel); // apply ViewModel
</script>

这篇关于从json模型中剔除JS更新视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆