More Related Content
Similar to 20131004 - Backbone js 介紹 by Bryan (20)
More from LearningTech (20)
20131004 - Backbone js 介紹 by Bryan
- 3. Introduction
Javascript MVC (Model-View-Controller) 框架
提供了非常簡單的方式創建模型 (model) 和視圖 (view) 幫助開發者可以很自然而
然的明確區隔使用者操作介面 (view) 的行為及背後資料處理 (model) 的邏輯
Backbone.js 的 model 是透過 observer pattern 的方式,讓 view 可以直接監聽
model 上的任何 event ,並且立刻更新 view 本身
支援 jQuery 或 Zepto 操作 DOM
提供支援 RESTful JSON interface 的 API
- 4. Model
Model 顧名思義是用來存放資料的類別,使用 Backbone 的 model 的好處是可以
很容易地和其他 Backbone 的類別作互動。
Backbone.js 的 constructor 的名字是 initialize
Person = Backbone.Model.extend({
initialize: function() {
console.log('hello world!');
}
});
- 7. Model
針對屬性給予預設值:
Person = Backbone.Model.extend({
initialize: function() {
console.log("hello world!");
},
defaults: {
name: "Scott",
height: "unknown"
}
});
- 9. Model
檢查 model 的正確性
Person = Backbone.Model.extend({
initialize: function() {
console.log('hello world!');
this.bind("change:name", function() {
console.log(persion.get('name'));
});
this.bind("error", function(model, error) {
console.log('error');
});
},
validate: function( attributes ) {
if (attributes.name == 'kenny' ) {
return 'Kenny is the founder of babylife';
}
},
});
- 10. View
initialize :View 的建構子
el :View 對應到的 DOM 物件
event:註冊事件
template 是指繪製 View 的時候可套用的template
render: 操作改變 el 的外觀
- 11. View
var myView = Backbone.View.extend({
initialize: function () {
console.log('create view');
},
el: '#container',
events: {
"click": "render"
},
template: $('#list-template').children(),
render: function() {
var data = this.model.get('data');
for (var i=0, l=data.length; i<l; i++) {
var a = this.template.clone().find('a');
var li = a.attr('href', data[i].href)
li = li.text(data[i].text).end();
this.$el.find('ul').append(li);
}
}
});