淘汰赛观察阵容不会改变

时间:2013-11-01 09:04:04

标签: knockout.js

这是我的代码:

<table>
  <tbody data-bind="foreach:Models">
     <tr>
         <td data-bind="text:Id"></td>
         <td data-bind="text:name"></td>
     </tr>
  </tbody>
</table>
function viewModel(){
   var self = this;
   self.Models = ko.observableArray();
}
var vm = new viewModel();

function mappingDatas(id){
  var results = [{ Id:1,name:"One" },{Id:2,name:"Two"}];
   if(id == 1)
   {
       results = [{ Id:3,name:"Three" },{Id:4,name:"Four"}];
   } 
   vm.Models = ko.mapping.fromJS(results);
   //vm.Models = ko.mapping.fromJS(results,vm.Models);//ie8 throw Stack overflow at line:4
   ko.applyBindings(vm);
}
$(function(){
   mappingDatas(0);
   $('#btn').click(function(){
      mappingDatas(1);
   })
});

代码可能正在运行,但是,当结果发生变化(btn click)时,它无法运行。错误是:“NotFoundError:未找到节点”。 我能怎么做?感谢!!!

1 个答案:

答案 0 :(得分:1)

我改变了你的js,似乎现在正在工作。更改结果数组后,您不需要再次applyBindings,您可以直接更新vm.Models。小提琴:http://jsfiddle.net/aW6yw/3/

JS:

function viewModel(){
   var self = this;
   self.Models = ko.observableArray();
}
var vm = new viewModel();

function mappingDatas(id){
  var results = [{ Id:1,name:"One" },{Id:2,name:"Two"}];
   if(id == 1)
   {
       results = [{ Id:3,name:"Three" },{Id:4,name:"Four"}];
   } 
    var vmResults = ko.mapping.fromJS(results);
   vm.Models(vmResults());

   //vm.Models = ko.mapping.fromJS(results,vm.Models);//ie8 throw Stack overflow at line:4
   //ko.applyBindings(vm);
}


   mappingDatas(0);
   $('#btn').click(function(){
      mappingDatas(1);
   })

ko.applyBindings(vm);