模型是一个用来表示应用程序数据的对象,它可能是一个简单的数组或通过RESTful API动态检索的数据;ember-data.js提供加载、映射和更新应用程序模型的API。
ember-data.js为每个应用程序都提供存储空间,存储空间负责保持已加载的Model和检索还未加载的Model。
前面,我们定义了应用程序App,现在,需要给程序提供数据也就是员工信息,所以我们要创建程序的模型(实体)Employee,接下来我们将实现模型的定义。
- // Defines a employee model.
- App.Employee = DS.Model.extend({
- name: DS.attr('string'),
- department: DS.attr('string'),
- title: DS.attr('string')
- })
上面,我们定义了Employee模型,它继承了DS.Model并且包含三个字段分别是name,department和title。
接下来,我们通过定义App.Employee.FIXTURES,模拟从服务器端获取数据。
- // Defines a JSON array.
- App.Employee.FIXTURES = [
- {
- id: 1,
- name: 'Jackson Huang',
- department: 'IT',
- title: 'programmer'
- },
- {
- id: 2,
- name: 'Ada Chen',
- department: 'purchasing',
- title: 'buyer'
- },
- {
- id: 3,
- name: 'JK Rush',
- department: 'IT',
- title: 'programmer'
- },
- {
- id: 4,
- name: 'Lucy Liu',
- department: 'IT',
- title: 'tester'
- },
- {
- id: 5,
- name: 'Julia Liu',
- department: 'HR',
- title: 'Manager'
- }
- ];
上面,我们定义了JSON数组App.Employee.FIXTURES,它包含了一系列员工的基本信息。
接下来,我们修改home和添加employee模板,具体实现如下:
- <!-- Home temp START -->
- <script type="text/x-handlebars" data-template-name="home">
- <h3>
- Employee Information</h3>
- <ul>
- {{#each item in content}}
- <li>{{item}}</li>
- {{/each}}
- </ul>
- <h3>
- Employee</h3>
- <ul>
- {{#each employee in employees}} {{#linkTo "employee" employee}}
- <p>
- {{employee.name}}
- </p>
- {{/linkTo}} {{/each}}
- </ul>
- </script>
- <!-- Home temp END -->
- <!-- Employee temp START -->
- <script type="text/x-handlebars" data-template-name="employee">
- <div>
- <h3>
- Name: {{name}}</h3>
- <p>
- Department: {{department}}
- </p>
- <p>
- Title: {{title}}
- </p>
- {{#linkTo home class='btn btn-primary'}}Back{{/linkTo}}
- </div>
- </script>
- <!-- Employee temp END -->
在home模板中,我们添加each表达式迭代访问employee元素,然后通过linkTo选择employee路由;然后根据路由选择在employee模板显示相应的员工信息。
程序页面
现在,我们完成了Employee程序的基本功能了,提供用户查下员工的信息了。
以上章节通过Demo例子介绍了Ember的使用,主要介绍了Ember的模型,控制器、模板和路由,由于Ember是Javascript MVC框架,而且作为初学者很容易困惑于它的自动生成和默认规则,所以我极力推荐大家要仔细看一遍Routing和Controller的官方文档。
我们通过介绍Ember的Handlerbars模板引擎,定义了Demo程序的页面,然后通过路由控制器定义路由行为,根据路由行为选择控制器,控制器负责数据加载和显示。但我们的例子中还没有设计的Ember视图模块,如果想进一步学习请参考官方文档或书籍。
参考
- http://www.adobe.com/cn/devnet/html5/articles/flame-on-a-beginners-guide-to-emberjs.html
- http://net.tutsplus.com/tutorials/javascript-ajax/getting-into-ember-js/?search_index=3
- http://emberjs.com/guides/
- http://xbingoz.com/emberguides/0.php
- http://andymatthews.net/read/2012/03/07/Getting-Started-With-EmberJS
以上四章节出处: http://www.cnblogs.com/rush/
转载本站内容时,请务必注明来自W3xue,违者必究。