knockout.js - lazy loading of templates

前端 未结 2 720
遇见更好的自我
遇见更好的自我 2020-12-13 01:00

So I come from a templating workflow that involves creating a data object (akin to a view model in knockout) passing that to a templating engine (jstemplate in our case), re

2条回答
  •  清歌不尽
    2020-12-13 01:46

    There are several directions that you can go for something like this:

    you can apply different view models to different elements, as you mentioned like:

    var viewModelOne = { ...  };
    var viewModelTwo = { ...  };
    ko.applyBindings(viewModelOne, containerElementOne);
    ko.applyBindings(viewModelOne, containerElementOne);
    

    You can even dynamically apply a binding with its data to an element like:

    var viewModelOne = { ... };
    ko.applyBindingsToNode(containerElement, { template: { name: 'itemTemplate', foreach: items }, viewModelOne);
    

    Would be like this sample: http://jsfiddle.net/rniemeyer/gYk6f/

    You can also do something like:

    var mainViewModel = {
       sideBarModel = ko.observable(),
       contentModel = ko.observable()
    };
    

    Then, bind it like:

    They, can even be nested like:

    ...

    Since, the models are observable, they can initially be empty and get populated on demand.

    You can certainly use named templates in those cases as well like:

    For the Extra Credit question:

    p tags cannot contain other block level elements (like your div). The browser moves it out of the p tag. Replace your div with a span and it will behave like you are expecting (or replace p with div).

提交回复
热议问题