我是 knockout 的新手。我已经有了这个 fiddle它将:
- 将左侧框填充为元素列表
- 一旦您在左框中选择了一个元素,它将在右框中显示详细的元素
看来我已经正确运行了。但我想添加更多内容。
- 加载后,选择第一个 foo 及其显示的详细信息
- 单击
+ 添加 foo
链接后,它将添加新的 foo 并突出显示,然后当我单击保存
时,右侧框中的编辑器将出现会将其添加到 foo 的集合中。
这可能吗?
下面的片段
var data = [
{ id: 1, name: "foo1", is_active: true },
{ id: 2, name: "foo2", is_active: true },
{ id: 3, name: "foo3", is_active: true },
{ id: 4, name: "foo4", is_active: false },
];
var FooBar = function (selected) {
this.id = ko.observable("");
this.name = ko.observable("");
this.is_active = ko.observable(true);
this.status_text = ko.computed(function () {
return this.is_active() === true ? "Active" : "Inactive";
}, this);
this.is_selected = ko.computed(function () {
return selected() === this;
}, this);
};
var vm = (function () {
var foo_bars = ko.observableArray([]),
selected_foo = ko.observable(),
load = function () {
for (var i = 0; i < data.length; i++) {
foo_bars.push(new FooBar(selected_foo)
.name(data[i].name)
.is_active(data[i].is_active)
.id(data[i].id));
}
},
select_foo = function (item) {
selected_foo(item);
},
add_foo = function () {
// I have tried this but ain't working at all. Please help
// foo_bars.push(new FooBar(selected_foo));
};
return {
foo_bars: foo_bars,
load: load,
selected_foo: selected_foo,
select_foo: select_foo,
add_foo: add_foo
};
}());
vm.load();
ko.applyBindings(vm);
.box {
float: left;
width: 250px;
height: 250px;
border: 1px solid #ccc;
}
.selected {
background-color: #ffa !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<div class="box">
<a href="#" data-bind="click: add_foo">+ Add foo</a>
<table>
<thead>
<tr>
<th>Name</th>
<th>Status</th>
</tr>
</thead>
<tbody data-bind="foreach: foo_bars">
<tr data-bind="click: $root.select_foo, css: { selected: is_selected }">
<td><a href="#" data-bind="text: $data.name"></a></td>
<td data-bind="text: $data.status_text"></td>
</tr>
</tbody>
</table>
</div>
<div class="box" data-bind="with: selected_foo">
Id: <span data-bind="text: id"></span><br />
Name: <input type="text" data-bind="value: name" /><br />
Status: <input type="checkbox" data-bind="checked: is_active"> <span data-bind="text: status_text"></span><br />
<button>Save</button>
</div>
最佳答案
演示:http://jsfiddle.net/wguhqn86/4/
load = function () {
for(var i = 0; i < data.length; i++){
foo_bars.push(new FooBar(selected_foo)
.name(data[i].name)
.is_active(data[i].is_active)
.id(data[i].id)
);
}
selected_foo(foo_bars()[0]); // default select first foo
},
add_foo = function() {
var count = foo_bars().length + 1;
var newItem = new FooBar(selected_foo).name('')
.is_active(true)
.id(count)
foo_bars.push(newItem);
selected_foo(newItem);
};
关于javascript - 如何将选定的可观察对象附加到新添加的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33368808/