»

Backbone.js notes

Coding, Log — Tags: , — Posted by Starck on October 18, 2013


Backbone.Events

Method Note
object.on(event, callback, [context]) 註冊監聽一個事件, 並指定觸發 callback, 如果需要在 callback function 中改變 this 的對象, 將對象傳入 context
object.off([event], [callback], [context]) 取消監聽事件, 不指定事件將取消所有的事件

Backbone Event Testing


Backbone.Model

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()
Properties / Method Note
model
url
models Raw access to the JavaScript array of models inside of the collection.
add
create
reset

Project Template


Backbone.View

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 JS Data Types Primer


Backbone.LocalStorage


Example: TodoList

Backbone TodoList

(c) 2024 Starck Lin | powered by WordPress