I have a very dynamic site, that uses custom applications/widgets within the page and I was researching how I might improve the site with the help of Knockout.
If each 'widget' is a viewModel that exist within the same tab(div), what kind of issues would I come across?
Is it ok to have one viewModel that starts at the top and contains other models? or should I have individual models and just use ko.applyBindings(vm, element) to apply them?
We've had success both ways, but typically we'll use the first scenario you mentioned, with one overall parent viewmodel containing instances of other, more specific, viewmodels. General practice suggests to avoid calling applyBindings
frequently. A quick mention of knockout's 'with' binding seems appropriate in your instance: http://knockoutjs.com/documentation/with-binding.html
That would keep the binding expressions within your tabs more focused to the viewmodels that they're representing:
<script type="text/javascript">
var ParentViewModel = function(){
this.tabOneViewModel = new TabOneViewModel();
this.tabTwoViewModel = new TabTwoViewModel();
}
var TabOneViewModel = function(){
this.tabOneTitle = 'Tab One';
}
var TabTwoViewModel = function(){
this.tabTwoTitle = 'Tab Two';
}
$(function(){
var parentViewModel = new ParentViewModel();
ko.applyBindings(parentViewModel,$('#main')[0]);
});
</script>
<body>
<div id="main">
<div data-bind="with:tabOneViewModel">
<div data-bind="text:tabOneTitle"></div>
</div>
<div data-bind="with:tabTwoViewModel">
<div data-bind="text:tabTwoTitle"></div>
</div>
</div>
</body>
Ultimately it's entirely up to you how you'd like to structure your dom and view models, just laying out a common example we've found useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With