依賴
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();
});