개발일기

Backbonejs - Model의 사용법 본문

Javascript/Backbone.js

Backbonejs - Model의 사용법

Flashback 2023. 1. 20. 22:53
728x90
반응형

1. 모델 객체 생성

import Backbone from 'backbone';

const FruitModel = Backbone.Model.extend({
	defaults: {
    	name: 'mango',
        price: '1000',
    }
}); // 모델 생성

const fruitModel = new FruitModel(); // 모델 객체 생성

Backbone.Model.extend({ }); 를 통해 모델을 생성할 수 있다. 모델을 생성한 후, new 연산자를 사용하여 모델 객체를 생성하여 사용한다.

 

2. 모델 속성 추가 및 출력

import Backbone from 'backbone';

const FruitModel = Backbone.Model.extend({
    defaults: {
        name: 'mango',
        price: '1000',
    }
}); // 모델 생성

const fruitModel = new FruitModel(); // 모델 객체 생성

fruitModel.set("count", 10); // 수량 추가
console.log(fruitModel.get('name')); // mango
console.log(fruitModel.get('count')); // 10

fruitModel.unset('price');
console.log(fruitModel.toJSON()); // {name: 'mango', count: 10}

fruitModel.clear();
console.log(fruitModel.toJSON()); // {}
  • set() : 모델 객체에 속성을 추가한다. 속성명 - 값을 순서대로 입력하여 추가한다.
  • get() : 해당 속성값을 조회한다.
  • unset() : 해당 속성값을 제거한다.
  • defaults : 모델의 기본값을 설정한다.
  • toJSON() : 모델에 속해있는 모든 속성을 객체 형식으로 출력한다.
  • clear() : 모든 속성값을 제거한다.

 

3. 모델 initialize 메서드

import Backbone from 'backbone';

const FruitModel = Backbone.Model.extend({
    defaults: {
        name: 'mango',
        price: '1000',
    },
    iniitialize: function() {
        console.log('fruit model init');
    }
}); // 모델 생성

const fruitModel = new FruitModel(); // 모델 객체 생성
// fruit model init

객체가 생성되거나 속성값이 변경되었을 때, 실행되는 초기화 메서드이다. 위와같이 모델 정의 후, 객체 생성을 하면 initialize 메서드가 실행되어 콘솔창에 'fruit model init'이라는 로그가 찍힌다.

 

initialize: function() {
    console.log('fruit model init');
    this.on('change', function() { // 속성값 변경 이벤트 발생시
        console.log('model attribute change');
    });
}
...

위와같이 initialize 메서드 안에 change 이벤트를 추가하면 모델의 속성값이 추가되거나 변경되면 콘솔에 로그가 찍히게  된다.

 


참고 사이트 :  

https://backbonejs.org/#Model

 

Backbone.js

Backbone.js gives structure to web applications by providing models with key-value binding and custom events, collections with a rich API of enumerable functions, views with declarative event handling, and connects it all to your existing API over a RESTfu

backbonejs.org

 

https://stackoverflow.com/questions/36206868/get-all-models-in-a-backbone-collection

 

Get all models in a backbone collection

I know there is a collection.models method that returns an array of the models. Is this the best practice to use or is there a way to return all models from a collection. The term raw is confusing...

stackoverflow.com

 

https://phsun102.tistory.com/135

 

Backbonejs - 요소의 정의 및 설치

1. Backbone.js 란? Backbone.js는 자바스크립트의 클라이언트 측 코드에서 SPA를 원활하게 개발할 수 있는 MV* 패턴의 프레임워크이자 자바스크립트 라이브러리다. Backbone.js는 컨트롤러가 없기에 MVC패턴

phsun102.tistory.com

 

728x90
반응형
Comments