Skip to content

Backbone.js 요약표 (Cheat Sheet)

이벤트 바인딩 (Binding Events)

.on('event', callback)
.on('event', callback, context)
.on({
  'event1': callback,
  'event2': callback
})
.on('all', callback)
.once('event', callback)   // 한 번만 실행되는 사용자 정의 이벤트 추가

이벤트 바인딩 해제 (Unbinding Events)

object.off('change', onChange)    // `onChange` 콜백만 해제
object.off('change')              // 모든 'change' 콜백 해제
object.off(null, onChange)        // 모든 이벤트의 `onChange` 콜백 해제
object.off(null, null, context)   // 지정된 `context`의 모든 이벤트에 대한 모든 콜백 해제
object.off()                      // 모두 해제

이벤트 트리거 (Trigger Events)

object.trigger('event')
view.listenTo(object, event, callback)
view.stopListening()

내장 이벤트 목록 (Built-in Events)

  • 컬렉션 (Collection):

    • add (model, collection, options)
    • remove (model, collection, options)
    • reset (collection, options)
    • sort (collection, options)
  • 모델 (Model):

    • change (model, options)
    • change:[attr] (model, value, options)
    • destroy (model, collection, options)
    • error (model, xhr, options)
  • 모델 및 컬렉션:

    • request (model, xhr, options)
    • sync (model, resp, options)
  • 라우터 (Router):

    • route:[name] (params)
    • route (router, route, params)

뷰 (Views)

뷰 정의

// 모든 속성은 선택 사항입니다
var View = Backbone.View.extend({
  model: doc,
  tagName: 'div',
  className: 'document-item',
  id: "document-" + doc.id,
  attributes: { href: '#' },
  el: 'body',
  events: {
    'click button.save': 'save',
    'click .cancel': function() { ··· },
    'click': 'onclick'
  },
  constructor: function() { ··· },
  render: function() { ··· }
})

뷰 인스턴스화 (View Instantiation)

view = new View()
view = new View({ el: ··· })

뷰 메서드 (View Methods)

view.$el.show()
view.$('input')
view.remove()
view.delegateEvents()
view.undelegateEvents()

모델 (Models)

모델 정의

// 모든 속성은 선택 사항입니다
var Model = Backbone.Model.extend({
  defaults: {
    'author': 'unknown'
  },
  idAttribute: '_id',
  parse: function() { ··· }
})

모델 인스턴스화 (Model Instantiation)

var obj = new Model({ title: 'Lolita', author: 'Nabokov' })
var obj = new Model({ collection: ··· })

모델 메서드 (Model Methods)

obj.id
obj.cid   // → 'c38' (클라이언트 측 ID)
obj.clone()
obj.hasChanged('title')
obj.changedAttributes()  // false 또는 hash
obj.previousAttributes() // false 또는 hash
obj.previous('title')
obj.isNew()
obj.set({ title: 'A Study in Pink' })
obj.set({ title: 'A Study in Pink' }, { validate: true, silent: true })
obj.unset('title')
obj.get('title')
obj.has('title')
obj.escape('title')     /* .get()과 같지만 HTML 이스케이프 처리됨 */
obj.clear()
obj.clear({ silent: true })
obj.save()
obj.save({ attributes })
obj.save(null, {
  silent: true, patch: true, wait: true,
  success: callback, error: callback
})
obj.destroy()
obj.destroy({
  wait: true,
  success: callback, error: callback
})
obj.toJSON()
obj.fetch()
obj.fetch({ success: callback, error: callback })

유효성 검사 (Validation)

var Model = Backbone.Model.extend({
  validate: function(attrs, options) {
    if (attrs.end < attrs.start) {
      return "Can't end before it starts"
    }
  }
})

{: data-line=“2”}

obj.validationError  //=> "Can't end before it starts"
obj.isValid()
obj.on('invalid', function (model, error) { ··· })
// 다음 경우에 트리거됨:
obj.save()
obj.set({ ··· }, { validate: true })

사용자 정의 URL (Custom URLs)

var Model = Backbone.Model.extend({
  // 단일 URL (문자열 또는 함수)
  url: '/account',
  url: function() { return '/account' },
  // 두 가지 모두 동일하게 작동함
  url: function() { return '/books/' + this.id }),
  urlRoot: '/books'
})
var obj = new Model({ url: ··· })
var obj = new Model({ urlRoot: ··· })