3. Page 3
Model
var Board = Backbone.Model.extend({
urlRoot: '/board', // restful api url
validate: function(attrs, options) { // 등록하는 데이터 유효성 검증은 여기서
var errorList = [];
if (attrs.writer== '') {
errorList.push({ name : 'writer', msg :" 작성자를 입력하세요 ."});
}
if (attrs.title == '') {
errorList.push({ name : 'title', msg :" 제목을 입력하세요 ."});
}
if (attrs.contents == '') {
errorList.push({ name : 'contents', msg :" 내용을 입력하세요 ."});
}
if (errorList.length > 0) {
return errorList;
}
},
parse: function(response) { // 조회한 데이터 중 데이터 변환은 여기서
response.insertDateTime = new Date(response.insertDateTime).format("Y-m-d");
return response;
}
});
4. Page 4
Collection
var BoardList = Backbone.Collection.extend({
model: Board, // 모델 객체
url: '/board', // restful api url
parse: function(response) {
return response;
}
});
5. Page 5
View - One
var BoardView = Backbone.View.extend({
initialize: function(){
// 모델에 이벤트 연결
this.model.on('change', this.render, this);
this.model.on('destroy', this.remove, this);
},
// 화면에 뿌려질 태그명 , 클래스명 설정
tagName: "li",
className: "list-group-item",
// 태그내에 뿌려진 템플릿 작성
template: _.template('<p><strong><%=title%></strong></p><span><%=writer%> | <%=insertDateTime%></span>'),
render: function(){
// 렌더링시 해당 템플릿에 데이터와 매핑하여 화면에 뿌려준다 .
this.$el.html(this.template(this.model.attributes));
this.$el.data('id', this.model.get('id'));
return this;
},
remove: function(){
console.log(this.$el);
this.$el.remove();
}
});
6. Page 6
View - List
var BoardListView = Backbone.View.extend({
initialize: function(){
// 모델에 이벤트 연결
this.collection.on('add', this.addOne, this);
this.collection.on('reset', this.addAll, this);
},
events: {
// click 과 같은 사용자 액션에 이벤트 연결
'click .list-group-item p strong' : 'renderModifiyView'
},
// 화면에 뿌려질 태그명 , 클래스명 설정
tagName: 'ul',
className: "list-group",
render: function() {
this.addAll();
return this;
},
// 한건이 등록되었을 경우 등록된 데이터를 랜더링하여 화면에 보여진다 .
addOne: function(board){
var boardView = new BoardView({model: board});
boardView.render();
this.$el.append(boardView.el);
},
// 전체 목록을 보여줄 경우 forEach 를 통해 addOne 을 호출하여 화면에 보여진다 .
addAll: function() {
this.collection.forEach(this.addOne, this);
$('#board-list tbody').remove();
$('#board-list').append(this.el); },
});
7. Page 7
View – List( 계속 )
// 수정페이지를 수정하려는 데이터를 가져와서 템플릿에 매핑하여 보여진다 ..
renderModifiyView: function(e){
var id = $(e.target).parent().parent().data('id');
var board = new Board({id : id});
board.fetch({success:function(model){
$("#updateBoardView").remove();
$("#boardAppView").append(_.template( $("#updateBoardViewTemplate").html(), model.attributes ));
$("#updateBoardView").data('id', model.get('id'));
$("#updateBoardView").modal({backdrop: false});
}});
}
9. Page 9
View – Main( 계속 )
// 등록 요청시 해당 콜렉션의 create 를 호출하여 등록한다 . 내부적으로 create 를 호출할 시 add 를 호출하며
(6 페이지에서 this.collection.on('add', this.addOne, this); -> 이미 이벤트로 연결되어 있어 화면은 자동으로
변경 되여 보여진다 .)
save : function(e){
e.preventDefault();
var baord = new Board({ writer : $('#boardInsertForm').find('input[name=writer]').val(),
title : $('#boardInsertForm').find('input[name=title]').val(),
contents : $('#boardInsertForm').find('textarea[name=contents]').val()});
// 유효성 검증
if (!baord.isValid()) {
baord.validationError.forEach(function(element){
$('#boardInsertForm').find('*[name=' + element.name + ']').attr('placeholder',
element.msg).parent().parent().addClass('has-error');
});
} else {
this.collection.create(baord, {wait:true});
this.close(e);
}
},
// 등록 팝업창 닫을 때 화면에 있는 데이터 초기화
close : function(e){
$('#' + $(e.target).parent().siblings('.modal-body').find('form').attr('id')).each(function(){
$(this).find('*[name]').each(function(){
$(this).val('');
if($(this).parent().parent().hasClass('has-error')) {
$(this).attr('placeholder', '').parent().parent().removeClass('has-error');
}
}) ;
});
console.log( $('#'+ $(e.target).parent().parent().parent().parent().attr('id')));
$('#'+ $(e.target).parent().parent().parent().parent().attr('id')).modal('hide');
10. Page 10
View – Main( 계속 )
// 데이터 초기화
clear : function(e){
var me = $(e.target);
if(me.parent().parent().hasClass('has-error')) {
me.attr('placeholder', '').parent().parent().removeClass('has-error');
}
},
// 수정 요청시 해당 모델의 save 를 호출하여 수정한다 . ( 내부적으로 save 를 호출할 시 change 를 호출하며
5 페이지에서 this.model.on('change', this.render, this); -> 이미 이벤트로 연결되어 있어 화면은 자동으로
변경 되여 보여진다 .)
update : function(e){
e.preventDefault();
var boardList = this.collection.where({ id : $("#updateBoardView").data('id')});
var me = this;
boardList.forEach(function(model){
model.set({ writer : $('#boardUpdateForm').find('input[name=writer]').val(),
title : $('#boardUpdateForm').find('input[name=title]').val(),
contents : $('#boardUpdateForm').find('textarea[name=contents]').val()});
if (!model.isValid()) {
model.validationError.forEach(function(element){
$('#boardUpdateForm').find('*[name=' + element.name + ']').attr('placeholder',
element.msg).parent().parent().addClass('has-error');
});
} else {
model.save();
me.close(e);
}
});
},
11. Page 11
View – Main( 계속 )
// 삭제 요청시 해당 모델의 destory 를 호출하여 삭제한다 .
(5 페이지에서 this.model.on('destroy', this.remove, this); -> 이미 이벤트로 연결되어 있어 화면은 자동으로
변경
되여 보여진다 .)
delete :function(e){
var boardList = this.collection.where({ id : $("#updateBoardView").data('id')});
boardList.forEach(function(model){
model.destroy();
});
this.close(e);
}
});
12. Page 12
예제 샘플은 요기 아래에 ~
https://github.com/eunsuklee/board_sample