这是代码knockout.js在主视图模型视图模型一个(新增项目是不确定的)
<form data-bind="submit: addItem">
New item:
<input data-bind='value: itemToAdd, valueUpdate: "afterkeydown"' />
<button type="submit" data-bind="enable: itemToAdd().length > 0">Add</button>
<p>Your items:</p>
<select multiple="multiple" width="50" data-bind="options: items"> </select>
这是视图模型
var SimpleListModel = function(items) {
this.items = ko.observableArray(items);
this.itemToAdd = ko.observable("");
this.addItem = function() {
if (this.itemToAdd() != "") {
this.items.push(this.itemToAdd()); // Adds the item. Writing to the "items" observableArray causes any associated UI to update.
this.itemToAdd(""); // Clears the text box, because it's bound to the "itemToAdd" observable
}
}.bind(this); // Ensure that "this" is always this view model
};
var masterVM = (function() {
var self = this;
self.SimpleListModel= new SimpleListModel(["Alpha", "Beta", "Gamma"]);
})();
ko.applyBindings(masterVM);
我必须有多个的ViewModels我页面。所以对于初学者,我创建了一个视图模型并将其放入一个主视图模型中。但addItem变得未定义。为什么是这样?我怎样才能使这种方法工作?
编辑
<div data-bind="with: viewModel2">
<div>
<span data-bind="text: boardtext" />
</div>
<a href="#" id="addVar" data-bind="click: addList ,visible: sh">Add a List</a><br /><br />
<form method="post">
<div data-bind="foreach: lists" id="thumbnails">
<div class="thumbnail-container">
<span data-bind="text:listname"></span><br /><br /><br /><br />
<div id="abc">
<ul class="list-group" data-bind="foreach: cardlists">
<li class="list-group-item">
<span data-bind="text: cardname"></span>
<a href="#" data-bind="click: $root.removecard">Del</a>
</li>
</ul>
<a href="#" data-bind="click: $parent.showhideaddcard,visible: cardvisiblity">Add Card</a><br />
<div data-bind="visible: showRenderTimes">
<input type="text" data-bind="value: $parent.cardtext" /><br /><br /><br />
<input type="button" value="Add" data-bind="click: $parent.addcard" />
<input type="button" value="Cancel" data-bind="click: $parent.cancelcard" />
</div>
<div data-bind="visible: showlist">
<input type="text" data-bind="value: $parent.listtext" /><br /><br />
<input type="button" value="Save list" data-bind="click: $parent.addbuttonlist" />
</div>
</div>
</div>
</div>
<p class="alignRight">
<input type="submit" value="Update">
</p>
</form>
</div>
有你的包裹里面的html用':SimpleListModel'? – muhihsan
我只是做了一个包装:SimpleListModel围绕此代码的一个div – maztt
它不起作用 – maztt