依赖
backbone依赖jquery/Zepto,underScore
创建项目的目录结构
1 lib/: 用于存放第三方库文件的目录,包括bcakbone、underscore、jquery
2 js/: 用于存放项目中用到的Js文件,包括main等
3 index.html
实例
$(document).ready(function() {
//model 模型
var InvoiceItemModel = Backbone.Model.extend({
defaults:{
price:0,
quantity:0
},
calculateAmount: function(){
return this.get('price') * this.get('quantity');
}
});
//View 模型
var PreviewInvoiceItemView = Backbone.View.extend({
// 下文中的\用于连接字符串
template:_.template('\
price:<%= price%>.\
Qunatity:<%= quantity%>.\
Amount:<%= amount%>.\
'),
render:function(){
var html = this.template({
price:this.model.get('price'),
quantity:this.model.get('quantity'),
amount:this.model.calculateAmount()
});
$(this.el).html(html);
}
});
//启动初始化
var invoiceItemModel = new InvoiceItemModel({
price:2,
quantity:3
});
var previewInvoiceItemView = new PreviewInvoiceItemView({
//使用这种方式绑定view与model
model:invoiceItemModel,
el:'body'
});
previewInvoiceItemView.render();
});
关于路由
继承于Router,定义routes来确定区分不同的
var Workspace = Backbone.Router.extend({
routes:{
'':'invoiceList',
'invoice':'invoiceList'
},
invoiceList:function(){
var invoiceListView = new InvoiceListView({
el:'body'
});
invoiceListView.render();
}
});
var InvoiceListView = Backbone.View.extend({
render:function(){
document.write('123456');
}
})
new Workspace();
Backbone.history.start();
});
网友评论