Here's the script: jsFiddle (see below for the script inline).
P
(Page) is a container for S
(Section) objects, and S
is a container for F
(Field) objects. When you click on "Add Section" you will get a new Section. Similarly you would get a new Field in the selected Section (currentSec
) when "Add Field to Section" is clicked.
I don't know if KO has a syntax for calling the addField()
function directly on the Section object -that's what I'm looking for. Evidently the current data-bind for the "Add Field" button is currently incorrect.
I know I can move addField()
to the Page object and have it use currentSec
to do its thing, but I'm wondering if I can keep my structure and still achieve the same result. I highly prefer to stick to my OOP best practices.
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());