Eungene's Imaginations...
[Backbone.js] Collection, add models and remove(reset) 본문
Programming/Backbone.js
[Backbone.js] Collection, add models and remove(reset)
Eungene's 2015. 10. 6. 10:48728x90
반응형
<script> var Book = Backbone.Model.extend({ initialize: function () { this.on("invalid", function (model, error) { console.log("**Validation Error : " + error + "**"); }); this.on("change", function (a) { // 로그를 남기는 여러가지 방법 console.log('Model Changed'); if (this.hasChanged('name')) { console.log('The name has changed'); } if (this.hasChanged('author')) { console.log('The author has changed'); } console.log('Changed attributes: ' + JSON.stringify(this.changed)); }); }, defaults: { name: 'Book Title', author: 'No One', year: 2000 }, // 개발자가 임의로 만든 함수 printDetails: function () { console.log('printDetails 함수 진입'); }, // attribute에 조건을 걸어둠. validate: function (attrs) { if (attrs.year < 2000) { // year attribute가 2000이하면 실행 return 'Year must be after 2000'; } if (!attrs.name) { // name attribute를 지울 경우 실행 return 'A name must be provided'; } } }); var Books = Backbone.Collection.extend({ model: Book, initialize: function () { this.on("remove", function (removedModel, models, options) { console.log('element removed at ' + options.index); }); } }); // 비어있는 동적배열 생성 var bookArray = []; console.log('배열생성'); bookArray[0] = new Book({ name: '책1', author: '띠모', year: '2015' }); bookArray[1] = new Book({ name: '책2', author: '똘뀌', year: '2011' }); bookArray[2] = new Book({ name: '책3', author: '페트루씨', year: '1965' }); bookArray[3] = new Book({ name: '책4', author: '존명씨', year: '1965' }); bookArray[4] = new Book({ name: '책5', author: '루데스씨', year: '1963' }); bookArray[5] = new Book({ name: '책6', author: '라브리에씨', year: '1967' }); var myBooks = new Books(); for (var i = 0; i < bookArray.length; i++) { // merge:true에 대한 기능 설명은 아래에... myBooks.add(bookArray[i], {merge:true}); } console.log('Library contains ' + myBooks.size() + ' books'); // {merge:true} ----> myBooks객체에 add 했던 model 객체가 다시 add된다면, // 다시 기존에 객체에 재 병합 해주는 기능을 한다. myBooks.add(bookArray[3], { merge: true }); // size()나 length 나 samesame~ //console.log('Library contains ' + myBooks.length + ' books'); console.log('Second Library contains ' + myBooks.size() + ' books'); // 해당 model 객체를 collection에서 지워준다. //myBooks.remove(bookArray[3]); //myBooks.remove(bookArray[1]); //reset은 괄호안에 삽입한 파라미터를 제외한 나머지 모델들을 지우는 메소드. myBooks.reset([bookArray[1], bookArray[3]]); console.log('Third library contains ' + myBooks.length + ' books'); ++ console.log('마지막 단'); </script>
반응형
Comments