빠른 참조

Spine.js 치트시트

Spine.js 빠른 참조 가이드: 모델, 클래스 및 인스턴스 메서드, 이벤트, Ajax 연동을 지원하는 JavaScript MVC 라이브러리.

· 게시일

모델 (Models)

모델 정의

class User extends Spine.Model
  @configure "User", "name", "address"

  fullName: ->
    [@first, @last].join ' '
// 순수 JavaScript 서브클래싱
var User = Spine.Model.sub();
User.configure("User", "name", "address");

모델 클래스 메서드

.configure 'modelname', attributes...

# Inheritance
.include(Module)
.extend(Module)

.create(name: "John")
.count()

# Events
.on 'refresh change', (user) -> ...
.trigger 'event'
.change (user) -> ...  # alias for on('change')
.fetch (user) -> ...   # alias for on('fetch')

# Serialization
.toJSON()         # all records
.fromJSON(json)   # from JSON string
.fromForm(el)

# Data properties
.records     # Hash of instances
.attributes  # array of attributes (from .configure)

# Lookups
.exists(1)
.find(1)     # throws error if not found
.select (u) -> u.name == 'bob'
.findByAttribute 'name', 'bob'
.findAllByAttribute 'name', 'bob'

.all()
.slice(6, 13)

# Deletion
.deleteAll()
.destroyAll()
.destroy(2)

인스턴스 메서드

user = new User()

user.isNew()
user.exists()

# Validation
user.isValid()
user.validate = -> "Name required" unless @name

user.attributes()  # hash of attribute values
user.eql(other)    # equality check

# Updates
user.load(attrs)
user.reload()
user.fromForm(form)
user.updateAttribute("name", "john")
user.updateAttributes(name: "John")

# Persistence & Clones
user.save()
user.destroy()
user.dup()         # clone unsaved record

Ajax 연동

Ajax 구성

class User extends Spine.Model
  @extend Spine.Model.Ajax

  @url: '/users'
  scope: '2013'

사용법

User.fetch()
user = new User()

user.url()            #=> "/users"
user.url('bands')     #=> "/users/bands"
user.scope = 'admin'
user.url()            #=> "/admin/users"

Ajax REST 매핑

Action HTTP Verb Endpoint
read GET /collection
create POST /collection (201 Created)
update PUT /collection/:id
destroy DELETE /collection/:id

연관 관계 (Associations)

class Photo extends Spine.Model
  @belongsTo 'album', 'Album'

class Album extends Spine.Model
  @hasMany 'photos', 'Photo'

album.photos().all()
album.photos().create(name: "Vacation")

참고자료

관련 주제