Example of knockoutjs pattern for multi-view applications [closed]
I am building an application that contains two complex, significantly different (yet with some shared components) views. One view allows the user to run queries and look at search results, and the other view gives an overview of recent activity. A related example might be a PIM app that has an email screen and a contacts screen. The two sets of operations are quite different, and yet there are also structural similarities between then. In building out my application, I have started with the search results view. I now need to create the second one, and am wondering about best practices in organizing the code.
Do I create a separate object (sub-view model, I guess) for each application "view" and toggle between them with if/ifnot bindings? One commonality between the views is that each has a scrollable, filterable, pageable list of objects. Should I try to factor out the differences between the lists so that I can have a common sort/filter UI, or do I just create two parallel interfaces that only share my custom bindings?
Thanks,
Gene
There are a few directions that you could go with this one.
One option is to call ko.applyBindings
with distinct view models against separate DOM elements like:
var viewModelA = { name: "Bob" };
var viewModelB = { price: 50 };
ko.applyBindings(viewModelA, document.getElementById("aContainer"));
ko.applyBindings(viewModelB, document.getElementById("bContainer"));
http://jsfiddle.net/9abgxn8k/
In this case, you would want to make sure that the elements are not ancestors of each other (don't want to bind anything twice)
Another option is to use sub view models:
var subModelA = { name: "Bob" };
var subModelB = { price: 50 };
var viewModel = {
subModelA: { name: "Bob" },
subModelB: { price: 50 }
};
ko.applyBindings(viewModel);
In this method, you would then use with
bindings on the areas that you want to display with each view model. You can control visibility with flags on the sub models or on the top model.
Another option that I like is to give your "views" a little bit of structure and do something like:
var View = function(title, templateName, data) {
this.title = title;
this.templateName = templateName;
this.data = data;
};
var subModelA = {
items: ko.observableArray([
{ id: 1, name: "one" },
{ id: 2, name: "two" },
{ id: 3, name: "three" }
])
};
var subModelB = {
firstName: ko.observable("Bob"),
lastName: ko.observable("Smith")
};
var viewModel = {
views: ko.observableArray([
new View("one", "oneTmpl", subModelA),
new View("two", "twoTmpl", subModelB)
]),
selectedView: ko.observable()
};
ko.applyBindings(viewModel);
http://jsfiddle.net/rniemeyer/PctJz/