这是我的代码
<div data-bind="foreach: baselist">
<div>
<span data-bind="text: basename"></span>
<div data-bind="foreach: subItems">
<span data-bind="text: subitemname"></span>
<a href="#" data-bind="click: $parent.removecard">Del</a>
</div>
</div>
<button data-bind="click:addChild">Add</button>
这是我的viewmodel
var SimpleListModel2 = function(baselist) {
this.baselist= ko.observableArray(baselist);
this.addChild = function(list) {
alert(list.basename());
}.bind(this);
self.removecard = function (cardlist) {
this.cardlists.remove(cardlist);
};
};
这是我传递给viewmodel的数据。如何在此数据中包含基本列表?它无法找到基本列表
var initialData = [{
{ basename: "Danny", subItems: [
{ subitemname: "Mobile"},
{ subitemname: "Home"}]
},
{ basename: "Sensei", subItems: [
{ subitemname: "Mobile"},
{ subitemname: "Home"}]
}];
答案 0 :(得分:1)
从你提供的html中,我可以看到结构是这样的。
baselist - &gt; {(baseName),(subItems - &gt; subitemName)}
因此,您似乎只需要在初始化期间将数据传递给viewModel。并在此处删除括号alert(list.basename);
,因为这不是可观察对象。
var SimpleListModel2 = function(baselist) {
this.baselist = ko.observableArray(baselist);
this.addChild = function(list) {
alert(list.basename);
}.bind(this);
};
var initialData = [
{ basename: "Danny", subItems: [
{ subitemname: "Mobile"},
{ subitemname: "Home"}]
},
{ basename: "Sensei", subItems: [
{ subitemname: "Mobile"},
{ subitemname: "Home"}]
}];
ko.applyBindings(new SimpleListModel2(initialData));
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div data-bind="foreach: baselist">
<div>
<span data-bind="text: basename"></span>
<div data-bind="foreach: subItems">
<span data-bind="text: subitemname"></span>
</div>
</div>
<button data-bind="click:$parent.addChild">Add</button>
</div>
&#13;