Backbone.js notes
Backbone.Events
|
1 2 |
var evtObj = {} _.extend( evtObj, Backbone.Events ); |
| Method | Note |
|---|---|
| object.on(event, callback, [context]) | 註冊監聽一個事件, 並指定觸發 callback, 如果需要在 callback function 中改變 this 的對象, 將對象傳入 context |
| object.off([event], [callback], [context]) | 取消監聽事件, 不指定事件將取消所有的事件 |
Backbone.Model
|
1 2 3 4 5 |
var Model = Backbone.Model.extend({ }); var ChildModel = Model.extend({ }); |
| Properties / Method | Note |
|---|---|
| constructor() | You can use Backbone.Model.apply(this, arguments) to invoke constructor function of parent class |
| initialize() | If you definean initialize function, it’ll be invoked when the model is created. |
| defaults | Remember that in JavaScript, objects are passed by reference, so if you include an object as a default value, it will be shared among all instances. Instead, define defaults as a function. |
| attributes | If you’d like to retrieve and munge a copy of the model’s attributes, use _.clone(model.attributes) instead. |
| validate(attrs, options) | By default validate is called before save, but can also be called before set if {validate:true} is passed. Return your custom error message, and it will be stored to validateError |
| isValid() | Run validate() to check the model state. |
| validationError | The value returned by validate during the last failed validation. |
set() get() |
set(‘attr’, ‘value’) or set({ attr: value}) |
| destroy() | You can use _.invoke() to call destroy function for a batch of models. ex: _.invoke(modelsArray, 'destroy') |
Backbone.Collection
- create({ attr: value })
- fetch()
|
1 2 |
var Collection = Backbone.Collection.extend({ }) |
| Properties / Method | Note |
|---|---|
| model | |
| url | |
| models | Raw access to the JavaScript array of models inside of the collection. |
| add | |
| create | |
| reset |
Backbone.View
|
1 2 |
var View = Backbone.View.extend({ }); |
| Properties / Method | Note |
|---|---|
| tagName | |
| id | |
| className | |
| attributes | |
| el and $el | |
| events | |
| render() | A good convention is to return this at the end of render to enable chained calls. |
Backbone.LocalStorage
|
1 |
localStorage: new Backbone.LocalStorage("SomeCollection"), // Unique name within your app. |