OSDN Git Service

Regular updates
[twpd/master.git] / backbone.md
1 ---
2 title: Backbone.js
3 layout: 2017/sheet
4 updated: 2018-12-06
5 category: JavaScript libraries
6 ---
7
8 ### Binding events
9
10 ```js
11 .on('event', callback)
12 .on('event', callback, context)
13 ```
14
15 ```js
16 .on({
17   'event1': callback,
18   'event2': callback
19 })
20 ```
21
22 ```js
23 .on('all', callback)
24 ```
25
26 ```js
27 .once('event', callback)   // Only happens once
28 ```
29
30 ### Unbinding events
31
32 ```js
33 object.off('change', onChange)    // just the `onChange` callback
34 object.off('change')              // all 'change' callbacks
35 object.off(null, onChange)        // `onChange` callback for all events
36 object.off(null, null, context)   // all callbacks for `context` all events
37 object.off()                      // all
38 ```
39
40 ### Events
41
42 ```js
43 object.trigger('event')
44 ```
45
46 ```js
47 view.listenTo(object, event, callback)
48 view.stopListening()
49 ```
50
51 ### List of events
52
53   * Collection:
54     * `add` (model, collection, options)
55     * `remove` (model, collection, options)
56     * `reset` (collection, options)
57     * `sort` (collection, options)
58
59   * Model:
60     * `change` (model, options)
61     * `change:[attr]` (model, value, options)
62     * `destroy` (model, collection, options)
63     * `error` (model, xhr, options)
64
65   * Model and collection:
66     * `request` (model, xhr, options)
67     * `sync` (model, resp, options)
68
69   * Router:
70     * `route:[name]` (params)
71     * `route` (router, route, params)
72
73 ## Views
74
75 ### Defining
76
77 ```js
78 // All attributes are optional
79 var View = Backbone.View.extend({
80   model: doc,
81 ```
82
83 ```js
84   tagName: 'div',
85   className: 'document-item',
86   id: "document-" + doc.id,
87   attributes: { href: '#' },
88 ```
89
90 ```js
91   el: 'body',
92 ```
93
94 ```js
95   events: {
96     'click button.save': 'save',
97     'click .cancel': function() { ··· },
98     'click': 'onclick'
99   },
100 ```
101
102 ```js
103   constructor: function() { ··· },
104   render: function() { ··· }
105 })
106 ```
107 ### Instantiating
108
109 ```js
110 view = new View()
111 view = new View({ el: ··· })
112 ```
113
114 ### Methods
115
116 ```js
117 view.$el.show()
118 view.$('input')
119 ```
120
121 ```js
122 view.remove()
123 ```
124
125 ```js
126 view.delegateEvents()
127 view.undelegateEvents()
128 ```
129
130 ## Models
131
132 ### Defining
133
134 ```js
135 // All attributes are optional
136 var Model = Backbone.Model.extend({
137   defaults: {
138     'author': 'unknown'
139   },
140   idAttribute: '_id',
141   parse: function() { ··· }
142 })
143 ```
144
145 ### Instantiating
146
147 ```js
148 var obj = new Model({ title: 'Lolita', author: 'Nabokov' })
149 ```
150
151 ```js
152 var obj = new Model({ collection: ··· })
153 ```
154
155 ### Methods
156
157 ```js
158 obj.id
159 obj.cid   // → 'c38' (client-side ID)
160 ```
161
162 ```js
163 obj.clone()
164 ```
165
166 ```js
167 obj.hasChanged('title')
168 obj.changedAttributes()  // false, or hash
169 obj.previousAttributes() // false, or hash
170 obj.previous('title')
171 ```
172
173 ```js
174 obj.isNew()
175 ```
176
177 ```js
178 obj.set({ title: 'A Study in Pink' })
179 obj.set({ title: 'A Study in Pink' }, { validate: true, silent: true })
180 obj.unset('title')
181 ```
182
183 ```js
184 obj.get('title')
185 obj.has('title')
186 obj.escape('title')     /* Like .get() but HTML-escaped */
187 ```
188
189 ```js
190 obj.clear()
191 obj.clear({ silent: true })
192 ```
193
194 ```js
195 obj.save()
196 obj.save({ attributes })
197 obj.save(null, {
198   silent: true, patch: true, wait: true,
199   success: callback, error: callback
200 })
201 ```
202
203 ```js
204 obj.destroy()
205 obj.destroy({
206   wait: true,
207   success: callback, error: callback
208 })
209 ```
210
211 ```js
212 obj.toJSON()
213 ```
214
215 ```js
216 obj.fetch()
217 obj.fetch({ success: callback, error: callback })
218 ```
219
220 ### Validation
221
222 ```js
223 var Model = Backbone.Model.extend({
224   validate: function(attrs, options) {
225     if (attrs.end < attrs.start) {
226       return "Can't end before it starts"
227     }
228   }
229 })
230 ```
231 {: data-line="2"}
232
233 ```js
234 obj.validationError  //=> "Can't end before it starts"
235 obj.isValid()
236 obj.on('invalid', function (model, error) { ··· })
237 ```
238
239 ```js
240 // Triggered on:
241 obj.save()
242 obj.set({ ··· }, { validate: true })
243 ```
244
245 ### Custom URLs
246
247 ```js
248 var Model = Backbone.Model.extend({
249   // Single URL (string or function)
250   url: '/account',
251   url: function() { return '/account' },
252 ```
253
254 ```js
255   // Both of these two work the same way
256   url: function() { return '/books/' + this.id }),
257   urlRoot: '/books'
258 })
259 ```
260
261 ```js
262 var obj = new Model({ url: ··· })
263 var obj = new Model({ urlRoot: ··· })
264 ```
265
266 ## References
267 {: .-one-column}
268
269 - [Backbone website](http://backbonejs.org/) _(backbonejs.org)_
270 - [Backbone patterns](http://ricostacruz.com/backbone-patterns/) _(ricostacruz.com)_