Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advice for a complex Knockout viewModel/models?

Tags:

knockout.js

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.

  • db <-namespace
    • tabs[] -> tab
      • id
      • title
      • type
      • items[] -> widget
        • id
        • css
        • privy
        • widget-specific viewModel
    • service

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?

like image 334
Zholen Avatar asked Oct 05 '12 19:10

Zholen


1 Answers

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.

like image 132
KodeKreachor Avatar answered Oct 24 '22 08:10

KodeKreachor