7. Model
• interactive한 데이터 관리로 가장 중요한 역할을 한다
- 동기화(Backbone.sync), JQuery.ajax를 사용한다.
• 각 모델은 고유의 URL을 가진다
8. Model
var Todo = context.todo = Backbone.Model.extend({
defaults: function() {
return {
title: "empty todo...",
order: Todos.nextOrder(),
done: false
};
},
// Toggle the `done` state of this todo item.
toggle: function() {
this.save({done: !this.get("done")});
}
});
9. Model
– extend
– constructor / initialize
– get
– set
– escape
– has
– unset
– clear
– id
– idAttribute
– cid
– attributes
– changed
– defaults
– toJSON
– sync
– fetch
– save
– destroy
– Underscore Methods (6)
– validate
– validationError
– isValid
– url
– urlRoot
– parse
– clone
– isNew
– hasChanged
– changedAttributes
– previous
– previousAttributes
fetch (HTTP GET)
save (HTTP POST, PUT)
destroy (HTTP DELETE)
get([attr])
set ([attr])
10. Collection
• Model의 집합
• 자료구조를 다룰 수 있는 다양한 함수들이 제공된다 (Underscore.js)
• Model과 동일하게 저장소와 동기화 된다
- 각 Model로 발생하는 이벤트는 Collection에게도 동일하게 전달
11. Collection
var TodoList = Backbone.Collection.extend({
// Reference to this collection's model.
model: Todo,
// Filter down the list of all todo items that are finished.
done: function() {
return this.where({done: true});
},
nextOrder: function() {
if (!this.length) return 1;
return this.last().get('order') + 1;
},
// Todos are sorted by their original insertion order.
comparator: 'order'
});