I've just began to explore knockout components, because our codebase was way before the components were introduced.
A few things I don't get at first read.
- How can one use an existing viewmodel at
component
binding? - To what should I bind when calling
applyBindings
?
Here is a quick example of what I mean.
function Customer() {
this.name = ko.observable();
...
this.orders = ko.observableArray([]);
}
Customer.prototype.addOrder = function(order) {
this.orders.push(order);
}
...
function Order() {
this.date = ko.observable();
...
}
...
// HERE I want the component binding in the foreach to use the $data
ko.components.register("Customer", {
viewModel: Customer,
template: "<strong data-bind='text: name'></strong><ul data-bind='foreach: orders'><li data-bind='component: "Order"'></li></ul>"
});
ko.components.register("Order", {
viewModel: Order,
template: "<span data-bind='text: date'></span>"
});
...
<!-- HERE I would like the component binding to use $data too -->
<div data-bind="component: 'Customer'"></div>
...
var customer = new Customer();
customer.name = "Test";
var order = new Order();
order.data = new Date();
customer.addOrder(order);
ko.applyBindings(customer);