Backbone.js 是一套 JavaScript 的 MVC 框架,拆成 Model(模型)、View(檢視)、Collection(集合)與 Router(路由)幾個部分。有 MVC 分層經驗的人會很容易上手。
它的價值在於:能在單一頁面上組織多個應用模組,讓使用者感覺不到頁面刷新,非常適合 webapp 類型的開發。
$(function(){
// Model:定義預設值
var testModel = Backbone.Model.extend({
defaults: {
id: "1",
name: 'meigong',
age: '22'
}
});
// Collection:某個 Model 的集合
var Collection = Backbone.Collection.extend({
model: testModel
});
// 單一列的 View
var ItemView = Backbone.View.extend({
tagName: 'tr',
template: _.template($('#tpl-item').html()),
initialize: function(){
this.model.bind('remove', this.unrender, this);
this.model.bind('change', this.render, this);
},
events: {
'click a.edit': 'editItem',
'click a.del': 'delItem',
'blur input,select': 'saveItem'
},
editItem: function(){
// 把該列所有 input 解鎖
var input = $(this.el).find('input');
input.each(function(k, v){ $(v).removeAttr('disabled'); });
},
delItem: function(){
app.collection.remove(this.model); // 從集合中移除
},
saveItem: function(){ /* 儲存邏輯 */ },
unrender: function(){ $(this.el).remove(); },
render: function(){
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
// 整個列表的 View
var View = Backbone.View.extend({
el: $('#test'),
template: _.template($('#tpl-student').html()),
initialize: function(){
this.render();
this.collection = new Collection();
this.collection.bind('add', this.appendItem, this);
this.id = 0;
},
events: { 'click #btn': 'addItem' },
addItem: function(){
this.id++;
this.testmodel = new testModel();
this.testmodel.set({ id: this.id });
this.collection.add(this.testmodel);
},
appendItem: function(){
var itemView = new ItemView({ model: this.testmodel });
$(this.el).append(itemView.render().el);
},
render: function(eventName){
$(this.el).html(this.template());
return this;
}
});
var app = new View();
});
1. 把 backbone-min.js 中的對應方法改為 create: "POST", update: "POST", "delete": "DELETE", read: "GET",以配合後端路由設定。
2. 服務端接收 POST 過來的 JSON 資料:$data = json_decode($GLOBALS['HTTP_RAW_POST_DATA']);
主檔案把 Model、Collection、Item View、List View 與 Router 串起來:
$(function(){
// ---- index 列表的 Model ----
var index_Model = Backbone.Model.extend({
url: "./get.php" // 請求位址
});
// ---- Model 的集合 ----
var index_Collection = Backbone.Collection.extend({
model: index_Model,
url: './get.php'
});
// ---- 對應每個元素的 View ----
var index_list_View = Backbone.View.extend({
template: _.template($('#tpl-item').html()),
initialize: function () {
// 執行 set / destroy 時會觸發 change
this.model.bind("change", this.render, this);
},
events: {
'click .bannerImg': 'addNum',
'click .bannerInfo': 'comment'
},
addNum: function(){
this.model.set({ 'name': '超姐你好' }); // 觸發 change
this.model.save(null, {
url: 'https://www.biuman.com/test/before/update2'
});
},
comment: function(){
var id = this.model.get('id');
app.navigate("comment/" + id, true); // hash 導航
},
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
// ---- list View:index_list_View 的集合 ----
var index_item_View = Backbone.View.extend({
initialize: function() {
// 這裡的 model 是個集合
this.model.bind('reset', this.render, this);
var self = this;
// 集合執行 add,或 create 請求成功時會觸發
this.model.bind("add", function (item) {
$(self.el).append(new index_list_View({ model: item }).render().el);
});
},
render: function(eventName) {
var self = this;
_.each(this.model.models, function(item) {
$(self.el).append(new index_list_View({ model: item }).render().el);
}, this);
return this;
}
});
// ---- 發表評論 ----
var comment_add_View = Backbone.View.extend({
template: _.template($('#tpl-comment').html()),
initialize: function(){ this.render(); },
events: { 'click .btn': 'addCom' },
addCom: function(){
var title = $("input[name='title']").val();
app.comment_collection.create({ title: title }, {
url: 'https://localhost/ci/before/insert2',
success: function(){}
});
},
render: function() {
// 沒有 model 時直接 this.template();有 model 則傳 this.model.toJSON()
$(this.el).html(this.template());
return this;
}
});
// ---- 評論列表 ----
var comment_Model = Backbone.Model.extend({
url: "./get.php",
defaults: { title: '' }
});
var comment_Collection = Backbone.Collection.extend({
model: comment_Model,
url: 'https://www.biuman.com/test/before/test'
});
var comment_list_View = Backbone.View.extend({
template: _.template($('#tpl-comment-list').html()),
initialize: function(){
this.model.bind("change", this.render, this);
},
render: function() {
$(this.el).html(this.template(this.model.toJSON()));
return this;
}
});
var comment_item_View = Backbone.View.extend({
initialize: function() {
this.model.bind('reset', this.render, this);
var self = this;
this.model.bind("add", function (item) {
$(self.el).append(new comment_list_View({ model: item }).render().el);
});
},
render: function(eventName) {
var self = this;
_.each(this.model.models, function(item) {
$(self.el).append(new comment_list_View({ model: item }).render().el);
}, this);
return this;
}
});
// ---- Router ----
var AppRouter = Backbone.Router.extend({
routes: {
"": "list",
"comment/:id": "comment"
},
list: function() {
if (typeof this.index_collection == 'undefined') {
this.index_collection = new index_Collection();
this.index_item_view = new index_item_View({ model: this.index_collection });
this.index_collection.fetch({
success: function(collection, resp){ /* 首次載入 */ }
});
} else {
this.index_item_view = new index_item_View({ model: this.index_collection });
}
$('#content').html(this.index_item_view.render().el);
},
comment: function(id) {
this.comment_collection = new comment_Collection();
this.comment_item_view = new comment_item_View({ model: this.comment_collection });
this.comment_collection.fetch({
url: 'https://www.biuman.com/test/before/test2/' + id,
success: function(collection, resp) {
$('#content').append(new comment_add_View().render().el);
}
});
$('#content').html(this.comment_item_view.render().el);
}
});
var app = new AppRouter();
Backbone.history.start();
});
1. 「綁定事件 → 觸發 → 自動重繪」是 Backbone 的核心循環。你不需要手動呼叫更新函式,只要 model.set() 改了值,訂閱了 change 的 View 就會自己重跑 render。這是它替你省下最多程式碼的地方。
2. 集合事件要綁在集合上。add 與 reset 是 Collection 的事件,不是 Model 的;而 change/destroy 屬於單一 Model。搞混這層就不會觸發。
3. fetch() 是異步的。上面 Router 的 comment() 裡,$('#content').html(...) 在 fetch 之前就執行了,因此畫面會先渲染空集合,資料到齊後才靠 add 事件逐筆補上。這是刻意的行為,但若不預期,很容易誤判成 bug。
4. 記得解綁。範例中大量使用 bind 卻沒有對應的 off,在長時間存活的路由切換中會累積殘留監聽,造成重複渲染。實務上應在離開路由時呼叫 view.remove() 或 stopListening()。
最後一點現實面的提醒:Backbone 如今已不再是新專案的首選,React、Vue 這類以元件為單位的方案在狀態管理上更直觀。但 Backbone 的 Model/Collection/View 分層依然值得讀一次——它會讓你更清楚「資料與畫面該如何分家」這個所有前端框架都在回答的問題。