2014-11-01 58 views
0

我有我的视图模型中的位置observableArray。UI不更新时,它应该

  1. 我使用locations数组创建复选框列表。
  2. 我还使用位置数组在UI中显示选中的位置。

当复选框被选中时,视图模型被更新。但是,显示的位置不会更新。

<ul data-bind="foreach: locations"> 
    <li data-bind="text: name, visible: checked"></li> 
</ul> 

<ul data-bind="foreach: locations"> 
    <li> 
     <input type="checkbox" data-bind="value: id, checked: checked" /> 
     <span data-bind="text: name"></span><br/> 
    </li> 
</ul> 
<br/> 
<button data-bind="click: debug">Debug</button> 
var locations = [ 
    {'id': 1, 'name': 'PP', 'checked': false}, 
    {'id': 2, 'name': 'Ta keo', 'checked': false}, 
    {'id': 3, 'name': 'Kompong Som', 'checked': true} 
]; 

var viewModel; 

viewModel = (function() { 
    function viewModel(locations) { 
     self = this; 
     this.locations = ko.observableArray(locations); 
     this.debug = function() { 
      alert(JSON.stringify(self.locations())); 
     }; 
    } 
    return viewModel; 
})(); 

ko.applyBindings(new viewModel(locations)); 

这里是一个小提琴: http://jsfiddle.net/bL7weqkz/

回答

1

checkedlocations变量需要财产可观察到,所以knockout.js可以当属性更新检测。将您的代码更改为:

var locations = [ 
    {'id': 1, 'name': 'PP', 'checked': ko.observable(false)}, 
    {'id': 2, 'name': 'Ta keo', 'checked': ko.observable(false)}, 
    {'id': 3, 'name': 'Kompong Som', 'checked': ko.observable(true)} 
]; 
+0

尽管如此,当它们映射到视图模型中时,使它们可观察将更为合适。 – 2014-11-01 22:31:47