20131004 - Backbone js 介紹 by Bryan
-
Upload
learningtech -
Category
Technology
-
view
295 -
download
3
description
Transcript of 20131004 - Backbone js 介紹 by Bryan
Backbone JS 介紹2013/10/04
Bryan Lin
Agenda
Introduction
Model
View
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
Model
Model 顧名思義是用來存放資料的類別,使用 Backbone 的 model 的好處是可以很容易地和其他 Backbone 的類別作互動。
Backbone.js 的 constructor 的名字是 initialize
Person = Backbone.Model.extend({
initialize: function() {
console.log('hello world!');
}
});
Model
可以直接新增 model 的屬性:var person = new Person({ name: "Joe", height: "6 feet" });
Model
取出剛才新增的屬性:person.get(‘name’)
Model
針對屬性給予預設值:Person = Backbone.Model.extend({
initialize: function() {
console.log("hello world!");
},
defaults: {
name: "Scott",
height: "unknown"
}
});
Model
綁定 change 事件 (change:name中間不可包含空格 )
Person = Backbone.Model.extend({
initialize: function() {
console.log("hello world!");
this.bind("change:name", function() {
console.log(person.get('name'));
});
}
//...
});
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';
}
},
});
View
initialize : View 的建構子 el : View 對應到的 DOM 物件 event:註冊事件 template 是指繪製 View 的時候可套用的 template
render: 操作改變 el 的外觀
Viewvar 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);
}
}
});