OSDN Git Service

Regular updates
[twpd/master.git] / modella.md
1 ---
2 title: Modella
3 category: JavaScript libraries
4 layout: 2017/sheet
5 prism_languages: [coffeescript]
6 intro: |
7   [Modella](https://www.npmjs.com/package/modella) allows you to create simple models in JavaScript. This is a guide on basic usage of Modella in CoffeeScript.
8 ---
9
10 ### Defining models
11
12 ```coffeescript
13 User = Modella('User')
14 ```
15
16 ```coffeescript
17   .attr('name')
18   .attr('email', { required: true })
19   .use(require('modella-validators'))
20 ```
21
22 ```coffeescript
23   .validator (u) ->
24     u.error('username', 'is required')  unless u.has('username')
25 ```
26
27 ### Instances
28
29 ```coffeescript
30 user
31   .name()
32   .name('John')
33   .set(name: 'John')
34 ```
35
36 ```coffeescript
37   .has('name')   # → true
38   .isNew()
39   .isValid()
40 ```
41
42 ```coffeescript
43   .save (err) ->
44   .remove (err) ->
45   .removed
46   .model         # === User
47 ```
48
49 ## Events
50
51 ### Emitting
52
53 ```coffeescript
54 Model.emit('event', [data...])
55 ```
56
57 ```coffeescript
58 record.emit('event', [data...])
59 ```
60
61 ### List of events
62
63 ```coffeescript
64 user
65   .on 'save', ->
66   .on 'create', ->
67   .on 'saving', (data, done) -> done()
68 ```
69
70 ```coffeescript
71   .on 'remove', ->
72   .on 'removing', (data, done) -> done()
73 ```
74
75 ```coffeescript
76   .on 'valid', ->
77   .on 'invalid', ->
78 ```
79
80 ```coffeescript
81   .on 'change', ->
82   .on 'change email', ->
83 ```
84
85 ```coffeescript
86   .on 'initializing', (instance, attrs) ->
87   .on 'initialize', ->
88 ```
89
90 ```coffeescript
91   .on 'error', -> failed to save model
92 ```
93
94 ```coffeescript
95   .on 'setting', (instance, attrs) ->  # on Model#set()
96   .on 'attr', -> # new attr via Model.attr()
97 ```
98
99 ## Misc
100
101 ### Plugins
102
103 ```coffeescript
104 MyPlugin = ->
105   return (Model) ->
106
107     Model.method = ...
108     Model.prototype.method = ...
109     Model.attr(...)
110
111     Model
112 ```
113
114 A plugin is a function that returns a model decorator (ie, a function that takes in a model and returns a model).
115
116 ### Memory
117
118 ```coffeescript
119 User
120   .all (err, users) ->
121   .find id, (err, user) ->
122 ```
123
124 ```coffeescript
125   .remove ->
126   .save ->
127   .update ->
128 ```