官术网_书友最值得收藏!

Managing templates with jQuery

Since we want to load templates from different files, let's move all our templates to a folder called views and make one file per template. Each file will have the same name the template has as an ID. So if the template has the ID, cart-item, the file should be called cart-item.html and will contain the full cart-item template:

<script type="text/html" id="cart-item"></script>
Managing templates with jQuery

The views folder with all templates

Now in the viewmodel.js file, remove the last line (ko.applyBindings(vm)) and add this code:

var templates = [
  'header',
  'catalog',
  'cart',
  'cart-item',
  'cart-widget',
  'order',
  'add-to-catalog-modal',
  'finish-order-modal'
];

var busy = templates.length;
templates.forEach(function(tpl){
  "use strict";
  $.get('views/'+ tpl + '.html').then(function(data){
    $('body').append(data);
    busy--;
    if (!busy) {
      ko.applyBindings(vm);
    }
  });
});

This code gets all the templates we need and appends them to the body. Once all the templates are loaded, we call the applyBindings method. We should do it this way because we are loading templates asynchronously and we need to make sure that we bind our view-model when all templates are loaded.

This is good enough to make our code more maintainable and readable, but is still problematic if we need to handle lots of templates. Further more, if we have nested folders, it becomes a headache listing all our templates in one array. There should be a better approach.

主站蜘蛛池模板: 肃南| 岗巴县| 绵竹市| 崇信县| 平阴县| 昌图县| 华亭县| 凌源市| 云安县| 宕昌县| 辽宁省| 海原县| 紫金县| 曲阳县| 桦南县| 崇阳县| 犍为县| 苏尼特右旗| 贡山| 萝北县| 利川市| 滦平县| 芮城县| 白城市| 右玉县| 巩留县| 德江县| 馆陶县| 白银市| 鄯善县| 沙雅县| 亚东县| 泰安市| 光山县| 漳平市| 温州市| 台山市| 齐河县| 邢台市| 南澳县| 南昌市|