Backbone.js Sync

Backbone Sync

Backbone.js의 Sync기능은 기본적으로 Restful한 서버에서 동작 하며, Ajax 데이터 전송을 당담한다.
CRUD method를 지원(‘create’, ‘read’, ‘update’, ‘delete’)

Backbone.sync is sync(method, model, [options]);

  • create -> POST /collection
  • read -> GET /collection[/id]
  • update -> PUT /collection/id
  • patch -> PATCH /collection/id
  • delete -> DELETE /collection/id

Backbone.Sync 메소드 테스트

다음과 같이 전역 Sync 메소드를 구현하면 원래의 Sync기능을 오버라이드 한다. 즉, Restful하지 않은 서버와 통신해야 할 때, 이 함수를 구현하면 된다.

1
2
3
4
5
Backbone.sync = function(method, model){
console.info('전역 Sync메소드 호출[s]');
console.info(method + ':' + JSON.stringify(model.toJSON(), '', 4));
console.info('전역 Sync메소드 호출[e]');
};

Backbone.Model.Sync, Backbone.Collection.Sync 메소드 테스트

이들 모두 오버라이드 가능한 sync메소드가 있다. 이 부분을 오버라이드 하면 Restful하지 않은 서버와 통신할 수 있게 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//모델 선언
var User = Backbone.Model.extend({
//모델 생성시의 초기값 설정
defaults: {
id:1,
name:'익명'
},
urlRoot: '/users',
idAttribute:'id',
//이 부분을 오버라이드 하면 Restful하지 않은 서버와 통신할 수 있게 됩니다.
sync:function(method, model, options){
console.info('모델의 Sync메소드 호출[s]');
console.info(method + ':' + JSON.stringify(model.toJSON(),'',4));
console.info('모델의 Sync메소드 호출[e]');
}
});

//모델 생성
var user = new User();
user.fetch(); //전체 리스트를 Read
user.at(0).fetch(); //레코드 1개를 Read
user.create({title:'999',category:'구구구'}); //레코드 1개를 Create
user.at(0).set({name:'변경된 이름'}).save(); //레코드 1개를 Update
user.at(0).remove(); //레코드 1개를 Delete

//모델 생성
var user2 = new User({id:2, name:'woonyzzang'}); // 모델생성과 동시에 신규모델 추가
user2.save(); //모델 업데이트
user2.destroy(); //모델 삭제
  • Backbone.sync, Backbone.Model.Sync, Backbone.Collection.Sync 함수를 구현해 주면 Restful하지 않은 서버를 대상으로도 Sync기능을 활용할 수 있다.
  • Backbone.Model과 Backbone.Collection의 defaults 프로퍼티에 id 어트리뷰트를 삽입하면 Sync의 create명령이 update명령으로 오동작할 수 있다.

참조

공유하기