0

这是我的代码:

<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:Node was not found”。我能怎么做?谢谢!!!

4

1 回答 1

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);  
于 2013-11-01T10:09:06.060 回答