Hoja de Referencia de Backbone.js
Vinculación de Eventos (Binding Events)
.on('event', callback)
.on('event', callback, context).on({
'event1': callback,
'event2': callback
}).on('all', callback).once('event', callback) // Añade un evento personalizado que se ejecuta solo una vez
Desvinculación de Eventos (Unbinding Events)
object.off('change', onChange) // solo el callback `onChange`
object.off('change') // todos los callbacks 'change'
object.off(null, onChange) // callback `onChange` para todos los eventos
object.off(null, null, context) // todos los callbacks para `context` todos los eventos
object.off() // todos
Disparar Eventos (Trigger Events)
object.trigger('event')view.listenTo(object, event, callback)
view.stopListening()Lista de Eventos Integrados (Built-in Events)
-
Colección (Collection):
add(model, collection, options)remove(model, collection, options)reset(collection, options)sort(collection, options)
-
Modelo (Model):
change(model, options)change:[attr](model, value, options)destroy(model, collection, options)error(model, xhr, options)
-
Modelo y colección:
request(model, xhr, options)sync(model, resp, options)
-
Enrutador (Router):
route:[name](params)route(router, route, params)
Vistas (Views)
Definir Vistas
// Todos los atributos son opcionales
var View = Backbone.View.extend({
model: doc, tagName: 'div',
className: 'document-item',
id: "document-" + doc.id,
attributes: { href: '#' }, el: 'body', events: {
'click button.save': 'save',
'click .cancel': function() { ··· },
'click': 'onclick'
}, constructor: function() { ··· },
render: function() { ··· }
})Instanciación de Vistas (View Instantiation)
view = new View()
view = new View({ el: ··· })Métodos de Vista (View Methods)
view.$el.show()
view.$('input')view.remove()view.delegateEvents()
view.undelegateEvents()Modelos (Models)
Definir Modelos
// Todos los atributos son opcionales
var Model = Backbone.Model.extend({
defaults: {
'author': 'unknown'
},
idAttribute: '_id',
parse: function() { ··· }
})Instanciación de Modelos (Model Instantiation)
var obj = new Model({ title: 'Lolita', author: 'Nabokov' })var obj = new Model({ collection: ··· })Métodos de Modelo (Model Methods)
obj.id
obj.cid // → 'c38' (ID del lado del cliente)
obj.clone()obj.hasChanged('title')
obj.changedAttributes() // false o hash
obj.previousAttributes() // false o hash
obj.previous('title')obj.isNew()obj.set({ title: 'A Study in Pink' })
obj.set({ title: 'A Study in Pink' }, { validate: true, silent: true })
obj.unset('title')obj.get('title')
obj.has('title')
obj.escape('title') /* Como .get() pero con escape de HTML */obj.clear()
obj.clear({ silent: true })obj.save()
obj.save({ attributes })
obj.save(null, {
silent: true, patch: true, wait: true,
success: callback, error: callback
})obj.destroy()
obj.destroy({
wait: true,
success: callback, error: callback
})obj.toJSON()obj.fetch()
obj.fetch({ success: callback, error: callback })Validación (Validation)
var Model = Backbone.Model.extend({
validate: function(attrs, options) {
if (attrs.end < attrs.start) {
return "Can't end before it starts"
}
}
}){: data-line=“2”}
obj.validationError //=> "Can't end before it starts"
obj.isValid()
obj.on('invalid', function (model, error) { ··· })// Se dispara en:
obj.save()
obj.set({ ··· }, { validate: true })URLs Personalizadas (Custom URLs)
var Model = Backbone.Model.extend({
// URL única (cadena o función)
url: '/account',
url: function() { return '/account' }, // Ambos funcionan de la misma manera
url: function() { return '/books/' + this.id }),
urlRoot: '/books'
})var obj = new Model({ url: ··· })
var obj = new Model({ urlRoot: ··· })