<div>模板绑定:</div>
1、script的顺序:jquery、temple、knockoutjs。<br>
在要写的div中用绑定data-bind="template:'scriptId'"绑定模板的ID。注意加上单引号。<br />
对应在script的标签中写< script type="text/html" id="scriptId" ><br />
在html中只写外层div,里面的循环显示部分放在script中显示。在html的div中写了内容也会被覆盖掉。<br />
2、对实例化对象的每一个进行排查放入div中,用{{each per}}。<br />
表达式用:{{ }}双引号,用each,直接写per,在viewmodel中定义的数组对象,把一组对象放在(per)其中。<br />
当each的内容不是数组对象时,在html中的绑定写成:data-bind="template:{name:'',data:viewData}"。在对应的script中写{{ each $data }}<br />
3、是否默认勾选用ko.observable(false)来实现。这些操作都不带括号。<br />
4、求长度是.length,没有括号。<br />
5、求时间:new Date().getSeconds()
6、在script中里层span的里层语句用()括号包括起来: <br />
(person rendered at< span data-bind="text: new Date().getSeconds()">< /span>)<br />
7、在模板的里层模板中的写法:
{ {each $data} }<br />
< li ><br />
$ { this }<br />
< span data-bind="visible: viewModel.showChild" ><br />
多了一个"$ ( this )"<br />
例子:模板的应用。点击添加循环增加相类似的部分。
<head>
<title></title><script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="js/jquery.tmpl.js"></script>
<script type="text/javascript" src="js/knockout-3.1.0.js"></script>
<style type="text/css">
</style>
</head>
<body>
<div data-bind="template:'personTemplate'">
</div>
<input type="checkbox" data-bind="checked:showChild" />show add child render time.
<script id="personTemplate" type="text/html">
<h2>person</h2>
<ul>
{{each per}}
<li>
<div>
<p>
${ name }has<span data-bind="text:children().length"> </span>children:
<a href="#" data-bind="click:add">add</a></p>
<span data-bind="visible:showChild">
(person rendered at<span data-bind="text:new Date().getSeconds()"></span>)
</span>
</div>
<div data-bind="template: { name: 'childrenTemplate', data: children }"></div>
</li>
{{/each}}
</ul>
</script>
<script id="childrenTemplate" type="text/html">
<ul>
{{each $data}}
<li>
${this}
<span data-bind="visible:viewModel.showChild">
(child rendered at <span data-bind="text:new Date().getSeconds()"></span>)
</span>
</li>
{{/each}}
</ul>
</script>
<script>
var person = function(name,children,x){ //以var person = function(p1,p2){}表达式的方式写模板的操作
this.name = name;
this.children = ko.observableArray(children);//数组对象用ko.observablArray。name不用ko.observable
this.add = function(){
this.children.push(x);
}.bind(this); //在function结束后带上.bind(this)
}
var viewModel ={
per:[
new person("firstOne",["fa","fab","fc","fd","fe"],"fo"),//模板实例化
new person("secondOne",["sa","sb","sc","sd","se"],"so"),
new person("thirdOne",["ta","tb","tc","td","te"],"to"),
],
showChild: ko.observable(false)
}
ko.applyBindings(viewModel);
</script>
</body>