修改observableArray中n个项目的特定可观察属性?

时间:2013-09-12 20:42:35

标签: knockout.js knockout-2.0

我正在做一个界面,当你点击它时,observableArray中的一个对象可以是selected。数组中任何当前selected个对象(其中只应有一个)应该可以更改其selected可观察对象。

我是否需要在点击时迭代整个数组,将所有selected设置为false,然后将点击的元素的selected设置为true,如此?

self.selectAnnotation = function() {
  var array = //annotations array from AnnotationsViewModel
  // (actually, I'm not so sure of the syntax of this either)

  for (var i = 0; i < array.length(); i++) {
    var item = array[i];
    item.selected(0);
  }
  self.selected(1);
}

使用如下所示的绑定:

<div id="clickArea" data-bind="foreach: annotations">   
    <span data-bind="click: selectAnnotation, css: selected: selected" class="annotation"></span>
</div>

1 个答案:

答案 0 :(得分:2)

您应该将所选项目存储在父上下文中,而不是存储在每个项目中。

var ViemModel = function(){
    var self = this;
    self.annotations= [...];
    self.selected = ko.observable();
    self.selectAnnotation = function(annotation) {
        self.selected(annotation);
    };
};

<div id="clickArea" data-bind="foreach: annotations">   
    <span data-bind="click: $parent.selectAnnotation, css: { 'selected': $parent.selected() == $data}" class="annotation"></span>
</div>

我希望它有所帮助。

相关问题