在本部分中,我们增加一个员工细节视图。由于现在该应用程序有一个以上的视图,我们也增加一个简单的视图路由机制。
打开index.html,并添加一个模板,以提供详细的员工视图:
<script id="employee-tpl" type="text/template"> <header class="bar bar-nav"> <a class="btn btn-link btn-nav pull-left" href="#"> <span class="icon icon-left-nav"></span> </a> <h1 class="title">Employee</h1> </header> <div class="content"> <div class="card"> <ul class="table-view"> <li class="table-view-cell media"> <img class="media-object pull-left emp-pic" src="assets/pics/{{pic}}"> <div class="media-body"> {{ firstName }} {{ lastName }} <p>{{ title }}</p> </div> </li> <li class="table-view-cell media"> <a href="tel:{{ officePhone }}" class="push-right"> <span class="media-object pull-left icon icon-call"></span> <div class="media-body"> Call Office <p>{{ officePhone }}</p> </div> </a> </li> <li class="table-view-cell media"> <a href="tel:{{ cellPhone }}" class="push-right"> <span class="media-object pull-left icon icon-call"></span> <div class="media-body"> Call Cell <p>{{ cellPhone }}</p> </div> </a> </li> <li class="table-view-cell media"> <a href="sms:{{ cellPhone }}" class="push-right"> <span class="media-object pull-left icon icon-sms"></span> <div class="media-body"> SMS <p>{{ cellPhone }}</p> </div> </a> </li> <li class="table-view-cell media"> <a href="mailto:{{ email }}" class="push-right"> <span class="media-object pull-left icon icon-mail"></span> <div class="media-body"> Email <p>{{ email }}</p> </div> </a> </li> </ul> </div> </div> </script>
1、在js目录创建一个命名为EmployeeView.js的文件,并定义它如下:
var EmployeeView = function(employee) { this.initialize = function() { this.$el = $('<div/>'); }; this.render = function() { this.$el.html(this.template(employee)); return this; }; this.initialize(); }2、在index.html中,增加一个脚本标签以包含EmployeeView.js(仅在app.js的脚本标签之前)。
<script src="js/EmployeeView.js"></script>步骤3:执行视图路由
1、在index.html中,增加一个脚本标签以包含router.js(仅在jquery.js的脚本标签之前)。
<script src="lib/router.js"></script>2、打开app.js。增加编译的员工模板到EmployeeView的原型:
EmployeeView.prototype.template = Handlebars.compile($("#employee-tpl").html());3、在应用程序中定义两个使用的路由:
service.initialize().done(function () { router.addRoute('', function() { $('body').html(new HomeView(service).render().$el); }); router.addRoute('employees/:id', function(id) { service.findById(parseInt(id)).done(function(employee) { $('body').html(new EmployeeView(employee).render().$el); }); }); router.start(); });4、测试应用程序。