Multiple viewing models per page and loading templates asynchronously

I am developing an application using - 1. Knockout.js 2. The engine of the external template Knockout.js (ifandelse) [indirectly using an infuser, trafficcop], 3, Sammy JS, Require JS, etc.

To increase the modularity and ease of development, I use the application to use several viewing models on the page. Using binding tips from Ryan Niemeyer ( http://www.knockmeout.net/2012/05/quick-tip-skip-binding.html), which describes how to link multiple view modes using the overloaded version of applyBindings. This technique worked fine until I decided to use the open source library for Jim Cowart's Knockout.js, which helps me extract templates to files and load them asynchronously. The reason this doesn’t work is simple: applyBinding to bind the viewmodel to a specific DOM element must have a DOM element present (this is not the case since the template is requested and loaded asynchronously by the KO External Template Engine). I can not use afterRender etc.

Has anyone come across this scenario? Any suggestion, direction in this regard will be very useful. Am I missing some KO feature that I can use?

Currently, when I work, I have added a templateLoaded callback when defining a template in HTML:

<!--ko template: {name: 'header', templateUrl: '/templates/shell', templateLoaded: function () { header.bindViewModel.call(header) }} -->
<!--/ko-->

HTML template:

<!-- ko stopBinding: true -->
<header id="divHeader">
    <!-- Template Code using Header viewmodel -->
</header>
<!-- /ko -->

Header View Mode:

bindViewModel = function () {
    ko.applyBindings(this, $("#divHeader").get(0));
}

and a modified Knockout.js "executeTemplate ()" method with the following parameters:

if (haveAddedNodesToParent) {
    if (options.templateLoaded ) {
        options.templateLoaded.call(bindingContext['$data']);
    }

    activateBindingsOnContinuousNodeArray(renderedNodesArray, bindingContext);
    if (options['afterRender'])
        ko.dependencyDetection.ignore(options['afterRender'], null, [renderedNodesArray, bindingContext['$data']]);
}

Now the callback is called after the template is retrieved asynchronously, parsed, and loaded into the DOM. This help binds the viewmodel to fix the item.

+5
source share
1 answer

I use the same architecture as on MVC4, in my work, the answer is easy Jyotindra uses applybindingsTonode and when you complete the request to the server, for example

  function loadMenu(){
       require('menu.js', function(menuViewmodel){
            ko.applyBindingsToNode(containerElement, { template: { name: 'itemTemplate', foreach: items }, menuViewmodel);
       }
    }

Hello! PS: you can also see this knockout.js - lazy template loading

+1
source

All Articles