Introduction to Backbone.js

Post on 17-May-2015

983 views 0 download

Tags:

description

Basics of the Backbone.js framework.

Transcript of Introduction to Backbone.js

introduction & patterns

Backbone.js

What is backbone.js

A Javascript MVC framework?

What is backbone.js

Almost.

What is backbone.js

Collection

Model

View

Router

Sync EventsSERVER

BROWSER

CTRL

Template

What is backbone.js

Collection

Model

View

Router

Sync EventsSERVER

BROWSER

CTRL

Template

Model

var Todo = Backbone.Model.extend({

urlRoot: “/api/todos”,

toggle: function() {this.save({done: !this.get("done")});

}});

var todo = new Todo({“id”: “1”});todo.fetch();todo.toggle();

What is backbone.js

Collection

Model

View

Router

Sync EventsSERVER

BROWSER

CTRL

Template

Collection

var Todos = Backbone.Collection.extend({

url: “/api/todos”,

model: Todo,});

var todos = new Todos();todos.fetch();

var todo = todos.get(“1”);todo.toggle();

What is backbone.js

Collection

Model

View

Router

Sync EventsSERVER

BROWSER

CTRL

Template

Events

var todos = new Todos();

todos.on(“change”, function(eventName, this) {console.log(“Todos changed”);

}, todos);

todos.fetch();

What is backbone.js

Collection

Model

View

Router

Sync EventsSERVER

BROWSER

CTRL

Template

Viewvar TodoView = Backbone.View.extend({

tagName: “li”, events: { “click .toggle”: “toggle”, },

initialize: function() {this.listenTo(this.model, “change”, this.render);

}, toggle: function() { this.model.toggle(); }

render: function() {this.$el.html(“<p><i class=’toggle’/>” + this.model.get(“name”) + ”

</p>”);}

});

View

var TodosView = Backbone.View.extend({initialize: function() {

this.listenTo(this.collection, “change”, this.render);},render: function() {

_.each(this.collection, function(todo) {this.$el.append(new TodoView({model: todo}).render());

});}

});

var todos = new Todos();var todosView = new TodosView({collection: todos});todos.fetch();

What is backbone.js

Collection

Model

View

Router

Sync EventsSERVER

BROWSER

CTRL

Template

Template

// underscore.js !

var TodoView = Backbone.View.extend({…template: _.template(...);render: function() {

this.$el.html(this.template(this.model.attributes));return this;

}});

What is backbone.js

Collection

Model

View

Router

Sync EventsSERVER

BROWSER

CTRL

Template

Router

var app = Backbone.Router.extend({routes: {

“/todos”: “todos”, // #/todos“/todos/:id”: “todo” // #/todos/1

},

todos: function() {...

},todo: function(id) {

...}

});

This is a lot of boilerplate code.

Fortunately backbone.js supports inheritance!

Backbone patterns.

Thank you

● @theorm

● https://github.com/theorm/backbone-recipes