Posted on 2016-04-02 12:06
笑看人生 阅读(839)
评论(0) 编辑 收藏
@import url(http://www.blogjava.net/CuteSoft_Client/CuteEditor/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
在学习笔记一中,一个视图渲染一个Sudent对象,如果存在多个Student对象怎么办,
在java中可以通过ArrayList来保存,比如List<Student> students = new ArrayList<>();
在Backbone中,也有类似于ArrayList的实现,只需要新建一个类,继承Collection就可以了,实现代码如下:
成员变量model指定集合中存放对象的类型,类似于java中范型。
1 var StudentCollection = Backbone.Collection.extend({
2 model: Student
3 });
对学习笔记一种代码稍加修改,修改代码如下:
新建三个Student对象,把这三个对象加入studentCollection对象中。
1 var student1 = new Student({
2 id: 10000,
3 name: '王小二',
4 age: 30
5 });
6
7 var student2 = new Student({
8 id: 20000,
9 name: '姚敏',
10 age: 26
11 });
12
13 var student3 = new Student({
14 id: 30000,
15 name: '科比',
16 age: 24
17 });
18
19 var studentCollection = new StudentCollection([
20 student1,
21 student2,
22 student3
23 ]);
至此集合模型已经新建完毕,那么如何通过视图来显示这个集合模型。
学习笔记一中新建的StudentView类的render方法做修改,同时在构建这个类对象时,稍作修改,修改如下:
把原来绑定model的代码改成绑定collection。
1 var studentCollectionView = new StudnetCollectionView ({
2 collection: studentCollection
3 });
1 var StudnetCollectionView = Backbone.View.extend({
2
3 el: 'body',
4
5 render:function(){
6 var html = '';
7 _.each(this.collection.models,function(model,index,obj){
8 var tmp = '学号: ' + model.get('id') + '.' +
9 '姓名: ' + model.get('name') + '.' +
10 '年龄: ' + model.get('age');
11
12 html = html + '<li>' + tmp + '</li>';
13 });
14
15 html = '<ul>' + html + '</ul>';
16 $(this.el).html(html);
17 }
18 });
完整的main.js内容如下:
1 (function($){
2 $(document).ready(function(){
3
4 var student1 = new Student({
5 id: 10000,
6 name: '王小二',
7 age: 30
8 });
9
10 var student2 = new Student({
11 id: 20000,
12 name: '姚敏',
13 age: 26
14 });
15
16 var student3 = new Student({
17 id: 30000,
18 name: '科比',
19 age: 24
20 });
21
22 var studentCollection = new StudentCollection([
23 student1,
24 student2,
25 student3
26 ]);
27
28 var studentCollectionView = new StudnetCollectionView({
29 collection: studentCollection
30 });
31
32 studentCollectionView.render();
33
34 });
35
36 //set model
37 var Student = Backbone.Model.extend({
38 //set default values.
39 defaults: {
40 id: 0,
41 name: '',
42 age: 0
43 }
44 });
45
46 var StudentCollection = Backbone.Collection.extend({
47 model: Student
48 });
49
50 //set view
51 var StudnetCollectionView = Backbone.View.extend({
52
53 el: 'body',
54
55 render:function(){
56 var html = "<table border='1'><tr><th>学号</th><th>姓名</th><th>年龄</th></tr>";
57 _.each(this.collection.models, function(model,index,obj){
58 var tmp = '<tr><td>' + model.get('id') + '</td>' +
59 '<td>' + model.get('name') + '</td>' +
60 '<td> ' + model.get('age') + '</td></tr>';
61
62
63 html = html = html + tmp;
64 });
65
66 html = html + '</table>';
67 $(this.el).html(html);
68 }
69 });
70
71 })(jQuery);
72