【发布时间】:2015-04-13 02:26:05
【问题描述】:
在嵌套的 foreach 中添加和删除时遇到问题。在这个例子中,我们有一个有很多房间的房子。每个房间都有许多家具。到目前为止,使用此代码,我可以正确显示数据并可以添加和删除房间,但我无法添加或删除家具。
HTML
//Other House fields work as expected above this section
<div data-bind='foreach: rooms'>
<button type="button" data-bind='visible: $root.rooms().length > 1, click: $root.removeRoom'> Remove Room </button>
<p> Room Name</p>
<input type="text" data-bind="value: name"></input>
//with: appears to work the same as a foreach -- neither seem to work
<div data-bind="with: furnitures">
<button type="button" data-bind='click: $root.rooms().furnitures().removeFurniture'> Remove Furniture </button>
<p> Furniture Name</p>
<input type="text" data-bind="value: name"></input>
</div>
<button type="button" data-bind='click: $root.rooms().furnitures().addFurniture'> Add Furniture </button>
</div>
<button type="button" data-bind='click: $root.addRoom'> Add Room </button>
JavaScript
var HouseModel = function(rooms) {
var self = this;
self.rooms = ko.observableArray(rooms);
// Not sure what to put here for Furniture because each room array item has an array of many furnitures
// ROOM MANAGEMENT ==========================
self.addRoom = function() {
self.rooms.push({
name:"",
furnitures[]: ""
});
};
self.removeRoom = function(room) {
self.rooms.remove(room);
};
// FURNITURE MANAGEMENT ==========================
// Not sure where this goes
self.addFurniture = function() {
self.furnitures.push({
name: ""
});
};
self.removeFurniture = function(furniture) {
self.furnitures.remove(furniture);
};
};
var viewModel = new HouseModel(rooms); // rooms are the pre-existing rooms and their furniture, in JSON format
ko.applyBindings(viewModel);
主要问题可能与按钮数据绑定的上下文以及模型的编码方式有关。有什么遗漏或错误。
感谢您的想法。
更新 这是一个问题: http://jsfiddle.net/zhLf1n61/
资源:
- Knockout nested view model(此示例不同,因为它没有嵌套视图模型)
- Knockout.JS official -working with collections(我发现这很难适用于我的情况)
【问题讨论】:
-
您能否也包括 Room 模型以及 AddFuniture 对您尝试做的事情最有意义的地方。也许即使是 jsfiddle 也是一个好主意
-
就是这样。没有房间模型;只有House模型。所以当数据传入时,它是一个 House 对象,带有一个 Room 数组,每个 Room 都有一个 Furnitures 数组。如果您暗示应该有另一个模型(Room one),那当然是有道理的,但我的理解是,在使用 Knockout 时,每页一个模型是可取的。如果我错了,请纠正我。
-
@Max 每页有多个视图模型没有错。特别是如果这些视图模型是模块化的可重用代码。
-
@Max 我添加了按钮绑定示例。
标签: javascript html knockout.js