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

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.

主站蜘蛛池模板: 昌黎县| 新田县| 望奎县| 庆阳市| 贡觉县| 昭平县| 云和县| 大兴区| 武隆县| 新蔡县| 东乡族自治县| 武邑县| 上蔡县| 甘谷县| 广丰县| 富蕴县| 万安县| 库尔勒市| 五华县| 漾濞| 屏南县| 揭西县| 南投县| 洞头县| 郴州市| 兴宁市| 和静县| 西乌珠穆沁旗| 托克逊县| 二连浩特市| 溧水县| 嘉善县| 祁门县| 嘉鱼县| 鹤山市| 都江堰市| 谢通门县| 乌什县| 陇南市| 清新县| 景洪市|