2013-07-23 51 views
0

在我的应用程序中,有一段动态加载的“位置”。位置是对象,而不是简单的字符串(它们具有名称,ID和其他属性)。我需要能够绑定到检查的位置,并且还想跟踪哪些在隐藏的输入中被检查,例如存储逗号分隔的locationId的字符串。使用KnockOutJS绑定复选框

我发现这里的一个很好的例子: Working with a list of checkboxes in knockoutjs

害得我这样的jsfiddle: http://jsfiddle.net/rniemeyer/Jm2Mh/

然而,当我试图用我的位置对象重新写这篇文章,它抛出一个错误:

Uncaught ReferenceError: Unable to parse bindings. 
Bindings value: attr: { value: $data }, checked: $item.selections 
Message: $item is not defined 

这是我到目前为止所做的一个JSFiddle。 (如果按F12并运行它,你可以看到上面的错误)。 http://jsfiddle.net/toddhd/BkUUX/3/

虽然错误是显而易见的,$ item没有定义,我真的不明白$ item是什么,它为什么它在第一个例子中,而不是我的。

感谢您提供任何帮助。如果有人可以帮助我重写代码以显示selectedLocations,也可以获得奖励积分。 :)

回答

1

$ Item不可用,因为它在基因敲除的默认模板机制中不受支持。这实际上是jQuery的一部分(请参阅答案here)。如果你想使用它,你将不得不重写默认的敲除模板机制。

这就是说,我在这里展示了另一种方法来做到这一点,而不需要here。本质上,只需为每个模型对象添加一个isSelected属性并解决这个问题,它肯定是最简单的路线。

var location = function (locationId, displayName, selected) { 
    var self = this; 
    self.LocationId = locationId; 
    self.DisplayName = displayName; 
    self.isSelected = ko.observable(selected); 

};

此外,小提琴演示如何显示选定的位置。

3

Here at Jsfiddle你会发现你的问题的工作解决方案,它也会显示选定的位置。

的HTML代码为:

<div data-bind="template: { name: 'locationTmpl', foreach: locations, templateOptions: { selections: selectedLocations } }">/</div> 
<script id="locationTmpl" type="text/html"> 

    <input type="checkbox" data-bind="attr: { value: $data }, checked: $data.isSelected" /> 
    <span data-bind="text: $data.DisplayName"></span> 
</script> 
<hr /> 
<div data-bind="text: JSON.stringify(ko.toJS(selectedLocations), null, 2)"></div> 
<hr /> 

JavaScript代码是:

<script type="text/javascript"> 
    function MyLocation(locationId, displayName, selected) { 
     this.LocationId = ko.observable(locationId); 
     this.DisplayName = ko.observable(displayName); 
     this.isSelected = ko.observable(selected); 
    } 

    var viewModel = function (items) { 
     this.locations = ko.observableArray([ 
      new MyLocation('1', 'Starbucks1'), 
      new MyLocation('2', 'Starbucks2', true), 
      new MyLocation('3', 'Starbucks3'), 
      new MyLocation('4', 'Starbucks4'), 
      new MyLocation('5', 'Starbucks5') 
     ]); 

     //self.selectedLocations = ko.observableArray([self.locations()[1]]);        
     this.selectedLocations = ko.computed(function() { 
      return ko.utils.arrayFilter(
       this.locations(), function (item) { 
        return item.isSelected(); 
       } 
       ); 
     }, this); 
    }; 

    ko.applyBindings(new viewModel()); 
</script> 

我已经介绍的相同的代码,博客,以及,你可以检查它by clicking this link

+0

谢谢伊姆兰。您的意见非常有帮助,我赞赏selectedLocations的额外细分。另一个答案得到了信誉,因为它是第一个,两个答案几乎相同,并且SethCran的selectedLocation更简洁一些。 –

+0

不客气托德!我很高兴这对你有一些帮助。问候 –