此文是延伸上文的Backbone.js的集合。
获取数据并不是立即发生的,所以为了创造更好的用户体验,应当加载一个图标告诉用户数据正在加载中。
(1)先映入三个文件库(JQuery.js、Underscore.js、BackBone.js)第一篇Backbone.js的文章《编写Backbone.js的第一个应用,相当于Hello World!》 有下载地址和版本号介绍
(2)准备两张图片分别叫(watermelon.jpg、orange.jpg和spinner.gif),放在img文件夹里
(3)在body里面添加一个<a/>标签
<a href="#collectionType/watermelon">watermelon</a>
(4)在html里添加一段js
<script>
//准备一些数据,会提供名称和图像的URL
var fruitData = [{name:"watermelon",url:"img/watermelon.jpg"},{name:"orange",url:"img/orange.jpg"}];
var app;
var router = Backbone.Router.extend({
routes:{
"":'fruit',
//用户浏览index.html#collectionType/名称时即可看到存储的某一个信息。
//这个信息由Backbone Router里定义的loadCollection函数获取和渲染
'collectionType/:collectionName':'loadCollection'
},
//创建Bacckbone Colelction使它和fruitData变量绑定,把集合传递给fruitView及collectionView
initialize:function(){
var collectionType = new CollectionType();
collectionType.reset(fruitData);
this.fruitView = new fruitView({collection:collectionType});
this.collectionView = new collectionView({collection:collectionType});
},
fruit:function(){
this.fruitView.render();
},
loadCollection:function(collectionName){
//this.collectionView.render(collectionName);
this.collectionView.loadCollection(collectionName);
}
});
//让fruitView可以使用整个数据库。
//现在只是把数据以JSON字符串的形式展示在浏览器中
var fruitView = Backbone.View.extend({
el:'body',
template:_.template('Fruit Data:<%=data%>'),
render:function(){
this.$el.html(this.template({data:JSON.stringify(this.collection.models)}));
}
});
//CollectionType的Backbone Collection非常干净
var CollectionType = Backbone.Collection.extend({});
//Fruit的视图只包含两个属性template和render
var collectionView = Backbone.View.extend({
/*
【相比较上一篇文章,新增的地方是下面的initialize、templateSpinner、loadCollection、showSpinner和注释掉加粗的两个地方】
*/
initialize:function(){
this.model = new (Backbone.Model.extend({}));
this.model.on('change',this.render,this);
this.on('spinner',this.showSpinner,this);
},
//为了让Underscore.js模板引擎可以更好的处理这个任务,需要给figure、img、figcaption标签展示特定的值
//为了保证阅读性,使用反斜杠作为结束符,或+来连接字符串
template:_.template('<figure>\<img src="<%=attributes.url%>"/>\<figcaption><%=attributes.name%></figcaption>\<figure>'),
templateSpinner:'<img src="img/spinner.gif" width="500">',
loadCollection:function(collectionName){
this.trigger('spinner');
var view = this;//需要在闭包里访问view
setTimeout(function(){
//模拟从远程服务器获取数据消耗的时间
view.model.set(view.collection.where({
name:collectionName
})[0].attributes);
},1000);
},
render:function(collectionName){
//用where方法和[]选择第一个元素作为模型
//var fruitModel = this.collection.where({name:collectionName})[0];
//var fruitHtml = this.template(fruitModel);
var fruitHtml = this.template(this.model);
$('body').html(fruitHtml);
},
showSpinner:function(){
$('body').html(this.templateSpinner);
}
});
$(document).ready(function(){
app = new router;
Backbone.history.start();
})
</script>
(5)具体实现效果:
a.在网页中可以看到用JSON展示的数据字符串
b.用index.html/#collectionType/watermelon会出现一个加载图片,然后1000后自动跳转到对应的图片和对应的名称
源代码免费提供给大家,希望大家一起交流学习。感谢。http://download.csdn.net/detail/miss_ll/9698745