This page is not available in every language. Missing translations are disabled in the language selector.

Quick reference

Spine Cheatsheet

Quick reference guide for Spine.js, an MVC library for JavaScript covering models, class methods, instances, events, and Ajax integration.

· Published

Models

Defining a Model

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

  fullName: ->
    [@first, @last].join ' '
// Vanilla JavaScript subclassing
var User = Spine.Model.sub();
User.configure("User", "name", "address");

Model Class Methods

.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)

Instance Methods

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 Integration

Ajax Configuration

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

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

Usage

User.fetch()
user = new User()

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

Ajax REST Mapping

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")

References

Related topics