- KnockoutJS Essentials
- Jorge Ferrando
- 218字
- 2021-07-23 20:16:17
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>

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.
- iOS 9 Game Development Essentials
- 深入淺出Java虛擬機(jī):JVM原理與實(shí)戰(zhàn)
- Learning Bayesian Models with R
- aelf區(qū)塊鏈應(yīng)用架構(gòu)指南
- Quarkus實(shí)踐指南:構(gòu)建新一代的Kubernetes原生Java微服務(wù)
- Visual C
- 精通網(wǎng)絡(luò)視頻核心開發(fā)技術(shù)
- Hands-On Full Stack Development with Go
- 深入淺出React和Redux
- Mastering openFrameworks:Creative Coding Demystified
- 用戶體驗(yàn)可視化指南
- 遠(yuǎn)方:兩位持續(xù)創(chuàng)業(yè)者的點(diǎn)滴思考
- 微信小程序開發(fā)邊做邊學(xué)(微課視頻版)
- Arduino Electronics Blueprints
- Flutter從0基礎(chǔ)到App上線