Backbone

Curso Profesional de Frontend - Mejorando.la



Julián David Duque
Developer by Passion
Engineer at Nodejitsu
http://about.me/julianduque



I <3 JS Community


MedellínJS

NodeBots

JSConf Colombia


Primer Acto



Models

// Define a Model
var Song = Backbone.Model.extend({});

// Instantiate a Model
var song = new Song({
name: "Marilyn Monroe",
author: "Pharrell Williams"
});

// Access properties
var name = song.get("name");
song.set({ author: "Pharrell" });

// Convert to JSON
song.toJSON();


Events

// Listen to an Event
song.on("event-name", doSomething);

// Trigger an Event
song.trigger("event-name");

// Model events
song.on("change:name", doSomething):



Views

var Song = Backbone.View.extend({
tagName: "li",
className: "item border-bottom",
template: Handlebars.compile($("#song-template").html()),
initialize: function () {
this.listenTo(this.model).on("change", this.render, this);
},

render: function () {
var song = this.model.toJSON()
var html = this.template(song);
this.$el.html(html);
return this;
}

});


Collections

var Songs = Backbone.Collection.extend({
model: Song
});

var songs = new Songs([ .... ]);

songs.forEach(doSomething);

songs.at(0);

songs.add(song);



Routers


var Router = Backbone.Router.extend({
routes: {
"": "index",
"album/:name": "album"
},

index: function () {},
album: function (name) {}
});

// Start Router
Backbone.history.start();




Next...

Best Practices!


Backbone

By Julián Duque

Backbone

Introduction to Backbone.js!

  • 3,501