DEV Community

Lam
Lam

Posted on

Modella Cheat Sheet

[Misc] Memory

User
  .all (err, users) ->
  .find id, (err, user) ->
Enter fullscreen mode Exit fullscreen mode
  .remove ->
  .save ->
  .update ->
Enter fullscreen mode Exit fullscreen mode

[Misc] Plugins

MyPlugin = ->
  return (Model) ->

    Model.method = ...
    Model.prototype.method = ...
    Model.attr(...)

    Model
Enter fullscreen mode Exit fullscreen mode

A plugin is a function that returns a model decorator (ie, a function that takes in a model and returns a model).

[Events] List of events

user
  .on 'save', ->
  .on 'create', ->
  .on 'saving', (data, done) -> done()
Enter fullscreen mode Exit fullscreen mode
  .on 'remove', ->
  .on 'removing', (data, done) -> done()
Enter fullscreen mode Exit fullscreen mode
  .on 'valid', ->
  .on 'invalid', ->
Enter fullscreen mode Exit fullscreen mode
  .on 'change', ->
  .on 'change email', ->
Enter fullscreen mode Exit fullscreen mode
  .on 'initializing', (instance, attrs) ->
  .on 'initialize', ->
Enter fullscreen mode Exit fullscreen mode
  .on 'error', -> failed to save model
Enter fullscreen mode Exit fullscreen mode
  .on 'setting', (instance, attrs) ->  # on Model#set()
  .on 'attr', -> # new attr via Model.attr()
Enter fullscreen mode Exit fullscreen mode

[Events] Emitting

Model.emit('event', [data...])
Enter fullscreen mode Exit fullscreen mode
record.emit('event', [data...])
Enter fullscreen mode Exit fullscreen mode

Instances

user
  .name()
  .name('John')
  .set(name: 'John')
Enter fullscreen mode Exit fullscreen mode
  .has('name')   # → true
  .isNew()
  .isValid()
Enter fullscreen mode Exit fullscreen mode
  .save (err) ->
  .remove (err) ->
  .removed
  .model         # === User
Enter fullscreen mode Exit fullscreen mode

Defining models

User = Modella('User')
Enter fullscreen mode Exit fullscreen mode
  .attr('name')
  .attr('email', { required: true })
  .use(require('modella-validators'))
Enter fullscreen mode Exit fullscreen mode
  .validator (u) ->
    u.error('username', 'is required')  unless u.has('username')
Enter fullscreen mode Exit fullscreen mode

Reference

Top comments (0)