I'm completely new to knockout. I have this sample set up where it will:
- Fill the left box with a list of items
- When you select an item in the left box, display its details in the right box
Seems like everything is working fine so far. But I want to enhance it further.
- On initial load, automatically select the first "foo" and show its details
- Clicking on the "+ Add foo" link should add a new "foo", highlight it, then show the editor in the right box. Once you click "save," it should add the new "foo" to the collection.
Is this achievable?
See code snippet below
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 () {
// Tried this but it's not working at all. Any help would be appreciated.
// 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>