【发布时间】:2014-05-06 07:40:39
【问题描述】:
这里是脚本:jsFiddle(内联脚本见下文)。
P (Page) 是 S (Section) 对象的容器,S 是 F (Field) 对象的容器。当您单击“添加部分”时,您将获得一个新部分。同样,当单击“将字段添加到部分”时,您将在所选部分 (currentSec) 中获得一个新字段。
我不知道 KO 是否有直接在 Section 对象上调用 addField() 函数的语法——这就是我要找的。显然,“添加字段”按钮的当前数据绑定当前不正确。
我知道我可以将addField() 移动到 Page 对象并让它使用currentSec 来做它的事情,但我想知道我是否可以保持我的结构并仍然获得相同的结果。我非常喜欢坚持我的 OOP 最佳实践。
HTML:
<div data-bind="foreach: secs">
<section class="section" data-bind="click: $parent.currentSec, attr: {id: id}">
<div data-bind="text: $data.id"/>
<ul data-bind="foreach: $data.fields">
<li data-bind="attr: {id: id}">New Field</li>
</ul>
</section>
</div>
<button data-bind="click: addSection">Add Section</button>
<div data-bind="with: currentSec">
<button data-bind="click: addField">Add Field to Section</button>
</div>
JS:
function P() {
this.id = 'pageId';
this.secs = ko.observableArray();
this.currentSec = ko.observable();
}
P.prototype.addSection = function() {
this.secs.push(new S("section" + this.secs().length));
}
function S(sid) {
this.id = sid;
this.fields = ko.observableArray();
this.currentField = ko.observable();
}
S.prototype.addField = function() {
this.fields.push(new F("field" + this.fields().length));
}
function F(fid) {
this.id = fid;
}
ko.applyBindings(new P());
【问题讨论】:
标签: knockout.js