Julián Duque
Developer and Educator
// 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();
// Listen to an Event
song.on("event-name", doSomething);
// Trigger an Event
song.trigger("event-name");
// Model events
song.on("change:name", doSomething):
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;
}
});
var Songs = Backbone.Collection.extend({
model: Song
});
var songs = new Songs([ .... ]);
songs.forEach(doSomething);
songs.at(0);
songs.add(song);
var Router = Backbone.Router.extend({
routes: {
"": "index",
"album/:name": "album"
},
index: function () {},
album: function (name) {}
});
// Start Router
Backbone.history.start();
By Julián Duque
Introduction to Backbone.js!