2. ¿Qué es Backbone?
● Librería JavaScript muy ligera para desarrollo de aplicaciones web
● Ofrece:
● Estructura de datos: Modelos y Colecciones
● Interfaz: Vistas y Rutas
● MVC
● RESTful
3. ¿Qué es Backbone?
● Librería JavaScript muy ligera para desarrollo de aplicaciones web
● Ofrece:
● Estructura de datos: Modelos y Colecciones
● Interfaz: Vistas y Rutas
● MV*
● RESTful
6. Modelo
var Todo = Backbone.Model.extend({});
var todo1 = new Todo();
console.log(JSON.stringify(todo1));
// Logs: {}
var todo2 = new Todo({
title: 'Check the attributes of both model instances in the
console.',
completed: true
});
console.log(JSON.stringify(todo2));
// Logs: {"title":"Check the attributes of both model instances in the
console.","completed":true}
7. Inicialización
var Todo = Backbone.Model.extend({
initialize: function(){
console.log('This model has been initialized.');
}
});
var myTodo = new Todo();
// Logs: This model has been initialized.
Modelo
8. Valores por defecto
var Todo = Backbone.Model.extend({
defaults: {
title: '',
completed: false
}
});
var todo2 = new Todo({
title: 'Check attributes of the logged models in the console.'
});
console.log(JSON.stringify(todo2));
// Logs: {"title":"Check attributes of the logged models in the
console.","completed":false}
Modelo
9. Get, set y toJSON
● Get
console.log(todo1.get('completed')); // false
● Set
myTodo.set("title", "Title attribute set through
Model.set().");
myTodo.set({
title: "Both attributes set through Model.set().",
completed: true
});
● ToJSON
var todo1Attributes = todo1.toJSON();
console.log(todo1Attributes);
// Logs: {"title":"","completed":false}
Modelo
10. Cambios en el modelo
var Todo = Backbone.Model.extend({
defaults: {
title: '',
completed: false
},
initialize: function(){
console.log('This model has been initialized.');
this.on('change', function(){
console.log('Values for this model have changed.');
});
this.on('change:title', function(){
console.log('Title value for this model has changed.');
});
}
});
Modelo
11. Validación
validate: function(attributes){
if(attributes.title === undefined){
return "Remember to set a title for your todo.";
}
},
initialize: function(){
console.log('This model has been initialized.');
this.on("invalid", function(model, error){
console.log(error);
});
}
var myTodo = new Todo();
myTodo.set('completed', true, {validate: true}); // logs: Remember to
set a title for your todo.
console.log(myTodo.get('completed')); // logs: false
console.log(myTodo.validationError) //logs: Remember to set a title
for your todo.
Modelo
17. Colecciones
var Todo = Backbone.Model.extend({
defaults: {
title: '',
completed: false
}
});
var TodosCollection = Backbone.Collection.extend({
model: Todo
});
var myTodo = new Todo({title:'Read the whole book', id: 2});
var todos = new TodosCollection([myTodo]);
console.log("Collection size: " + todos.length); // Collection size: 1
18. Añadir, obtener y eliminar modelos
var a = new Todo({ title: 'Go to Jamaica.', id:1}),
b = new Todo({ title: 'Go to China.', id:2}),
c = new Todo({ title: 'Go to Disneyland.', id:3});
var todos = new TodosCollection([a,b]);
console.log("Collection size: " + todos.length);
// Logs: Collection size: 2
todos.add(c);
console.log("Collection size: " + todos.length);
// Logs: Collection size: 3
todos.remove([a,b]);
console.log("Collection size: " + todos.length);
// Logs: Collection size: 1
var todo2 = todos.get(2);
// logs: { title: 'Go to China.', id:2}
Colecciones
19. Actualizando
var TodosCollection = new Backbone.Collection();
TodosCollection.add([
{ id: 1, title: 'go to Jamaica.', completed: false },
{ id: 2, title: 'go to China.', completed: false },
{ id: 3, title: 'go to Disneyland.', completed: true }
]);
TodosCollection.set([
{ id: 1, title: 'go to Jamaica.', completed: true },
{ id: 2, title: 'go to China.', completed: false },
{ id: 4, title: 'go to Disney World.', completed: false }
]);
Console.log(TodosCollection.toJSON());
// Logs: [ { id: 1, title: 'go to Jamaica.', completed: true },
// { id: 2, title: 'go to China.', completed: false },
// { id: 4, title: 'go to Disney World.', completed: false } ]
Colecciones
20. Eventos
var TodosCollection = new Backbone.Collection();
TodosCollection.on("change:title", function(model) {
console.log("Changed my mind! I should " + model.get('title'));
});
TodosCollection.add([
{ title: 'go to Jamaica.', completed: false, id: 3 },
]);
var myTodo = TodosCollection.get(3);
myTodo.set('title', 'go fishing');
// Logs: Changed my mind! I should go fishing
Colecciones
26. RESTful Persistence
var Todo = Backbone.Model.extend({
defaults: {
title: '',
completed: false
}
});
var TodosCollection = Backbone.Collection.extend({
model: Todo,
url: '/todos'
});
var todos = new TodosCollection();
todos.fetch(); // sends HTTP GET to /todos
var todo2 = todos.get(2);
todo2.set('title', 'go fishing');
todo2.save(); // sends HTTP PUT to /todos/2
todo2.destroy(); // sends HTTP DELETE to /todos/2
todos.create({title: 'Try out code samples'}); // sends HTTP POST
to /todos
27. BackBone-sync
Backbone.sync = function(method, model, options) {
switch (method) {
case 'POST':
return MyAPI.create(model, success, error);
case 'PUT':
return MyAPI.update(model, success, error);
case 'PATCH':
return MyAPI.patch(model, success, error);
case 'DELETE':
return MyAPI.destroy(model, success, error);
case 'GET':
if (model.cid) {
return MyAPI.find(model, success, error);
} else {
return MyAPI.findAll(model, success, error);
}
}