Knockoutjs属性绑定(Bindings)之模板绑定(template binding)

关于Knockoutjs属性绑定的内容我们基本上已经介绍完了,最后我们再介绍一下属性绑定的最后一个模块,那就是模板绑定(template binding)。我们使用模板绑定的目的就是可以将复杂的页面通过各个模板为我们分别实现,当我们使用这些模板的使用通过模板绑定即可使用,这样对我们页面的编写也是十分方便的,我们使用模板的情况大多是内容是重复性的或者是分块嵌套的,这样对View Model层的数据展示就非常的方便。

下面我们就借助几个例子看看怎样使用模板绑定。

(1)、使用name来render模板

 1 <h2>Participants</h2>
 2 Here are the participants:
 3 <div data-bind="template: { name: 'person-template', data: buyer }"></div>
 4 <div data-bind="template: { name: 'person-template', data: seller }"></div>
 5  
 6 <script type="text/html" id="person-template">
 7     <h3 data-bind="text: name"></h3>
 8     <p>Credits: <span data-bind="text: credits"></span></p>
 9 </script>
10  
11 <script type="text/javascript">
12      function MyViewModel() {
13          this.buyer = { name: 'Franklin', credits: 250 };
14          this.seller = { name: 'Mario', credits: 5800 };
15      }
16      ko.applyBindings(new MyViewModel());
17 </script>

在本例中,我们两次使用了person-template模板,第一次使用传递的是buyer数据,第二次使用传递的是seller数据。在这里我们要注意的是,我们在定义模板的时候我们使用的是<script type="text/html">,属性type的值确保了此标签不会作为JavaScript代码执行,而是作为一段HTML代码来执行。

(2)、使用foreach配合上例

 1 <h2>Participants</h2>
 2 Here are the participants:
 3 <div data-bind="template: { name: 'person-template', foreach: people }"></div>
 4  
 5 <script type="text/html" id="person-template">
 6     <h3 data-bind="text: name"></h3>
 7     <p>Credits: <span data-bind="text: credits"></span></p>
 8 </script>
 9  
10  function MyViewModel() {
11      this.people = [
12          { name: 'Franklin', credits: 250 },
13          { name: 'Mario', credits: 5800 }
14      ]
15  }
16  ko.applyBindings(new MyViewModel());

这里我们使用的是foreach来调用我们的模板,此时只使用了一次我们的person-template模板,这段代码和下面的代码所实现的功能是一样的:

1 <div data-bind="foreach: people">
2     <h3 data-bind="text: name"></h3>
3     <p>Credits: <span data-bind="text: credits"></span></p>
4 </div>

(3)、我们也可以为foreach所循环的元素定义一个别名,我们使用as为其定义别名。如下:

1 <ul data-bind="template: { name: 'employeeTemplate',
2                                   foreach: employees,
3                                   as: 'employee' }"></ul>

这里我们定义别名的目的就是在多层嵌套中可以很方便的使用上层循环中的内容,我们在之前讲解foreach的时候曾经提到了使用$parent来调用上层循环中的内容,这里我们使用as为foreach中的循环元素起了个别名,这样我们就可以使用这个别名来访问其中的内容了,如下例子:

 1 <ul data-bind="template: { name: 'seasonTemplate', foreach: seasons, as: 'season' }"></ul>
 2  
 3 <script type="text/html" id="seasonTemplate">
 4     <li>
 5         <strong data-bind="text: name"></strong>
 6         <ul data-bind="template: { name: 'monthTemplate', foreach: months, as: 'month' }"></ul>
 7     </li>
 8 </script>
 9  
10 <script type="text/html" id="monthTemplate">
11     <li>
12         <span data-bind="text: month"></span>
13         is in
14         <span data-bind="text: season.name"></span>
15     </li>
16 </script>
17  
18 <script>
19     var viewModel = {
20         seasons: ko.observableArray([
21             { name: 'Spring', months: [ 'March', 'April', 'May' ] },
22             { name: 'Summer', months: [ 'June', 'July', 'August' ] },
23             { name: 'Autumn', months: [ 'September', 'October', 'November' ] },
24             { name: 'Winter', months: [ 'December', 'January', 'February' ] }
25         ])
26     };
27     ko.applyBindings(viewModel);
28 </script>

上例中我们分别为seasons、months起名为season、month,这样我们在引用monthTemplate模板时我们就可以使用season.name来引用seasonTemplate模板中的season的信息了。

(4)、动态选择模板

有的时候我们可能有多个模板,此时我们就可以使用一个回调函数来决定使用哪一个模板,比如:

 1 <ul data-bind='template: { name: displayMode,
 2                            foreach: employees }'> </ul>
 3  
 4 <script>
 5     var viewModel = {
 6         employees: ko.observableArray([
 7             { name: "Kari", active: ko.observable(true) },
 8             { name: "Brynn", active: ko.observable(false) },
 9             { name: "Nora", active: ko.observable(false) }
10         ]),
11         displayMode: function(employee) {
12             // Initially "Kari" uses the "active" template, while the others use "inactive"
13             return employee.active() ? "active" : "inactive";
14         }
15     };
16  
17     // ... then later ...
18     viewModel.employees()[1].active(true); // Now "Brynn" is also rendered using the "active" template.
19 </script>

如果你的函数引用的是可见值,则这些值改变时,你的模板绑定的值也会改变,并会重新加载模板。

(5)、我们也可以在Knockoutjs中使用其他的模板引擎,比如jQuery.tmpl等。

我们这里以使用jQuery.tmpl为例,如果我们要使用jQuery.tmpl模板引擎的话,我们首先要先引用下面的一些js,代码如下:

1 <!-- First jQuery -->     <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
2 <!-- Then jQuery.tmpl --> <script src="http://github.com/downloads/SteveSanderson/knockout/jquery.tmpl.js"></script>
3 <!-- Then Knockout -->    <script src="knockout-x.y.z.js"></script>

然后我们就可以使用jQuery.tmpl的规则去编写代码了,如下:

 1 <h1>People</h1>
 2 <div data-bind="template: 'peopleList'"></div>
 3  
 4 <script type="text/html" id="peopleList">
 5     {{each people}}
 6         <p>
 7             <b>${name}</b> is ${age} years old
 8         </p>
 9     {{/each}}
10 </script>
11  
12 <script type="text/javascript">
13     var viewModel = {
14         people: ko.observableArray([
15             { name: 'Rod', age: 123 },
16             { name: 'Jane', age: 125 },
17         ])
18     }
19     ko.applyBindings(viewModel);
20 </script>

在这里我们使用的{{each ...}}和${...}都是jQuery.tmpl的语法规则,并且我们可以使用data-bind="template:..."去加载这个模板。

原文地址:https://www.cnblogs.com/wukong65/p/2800586.html