Sie sind auf Seite 1von 19

Intro to Backbone.

js
Event-driven MVC for complex JavaScript web applications

Michael Lovitt Lead Developer, SB Nation michael@sbnation.com | @lovitt

Agenda

Why Backbone? What problems does it solve? How does it solve these problems? Code: working with models and views Questions (feel free to ask during the talk)

Why Backbone?

Need for Structure


Without the right approach, JavaScriptheavy web applications devolve into unmaintainable spaghetti

Why is this?

Client Responsibilities
During a user session, the JS front-end is: Keeping track of the users actions (via Updating relevant bits of the UI Periodically sending updates to (and
the DOM or by stashing data in its own JS objects)

processing responses from) the server

Impending Doom

A rich client-side app must do a lot on its own. When the user takes an action, the app often responds directly, without talking to the server The app must be smart and stateful. It manages both the app state and the views on that state

In a complex app, a single user action may trigger many state changes; and a single state change may trigger many UI changes Code can get ugly as it tries to glue all of these pieces together This sucks

Backbone Approach

Event-Driven MVC

Backbone is an MVC framework Models re events when they change UI is divided up into views that can listen to models State changes are made in the model only

Views are notied and update themselves when models theyre listening to change So models can be decoupled from views, and views decoupled from each other This is pretty sweet

What else?
Controllers that route URLs to views ERB-style templates for rendering views
(actually from Underscore.js) with the server apps

Standard means to sync client-side data Clear path to structuring large, complex JS

When to use Backbone?


When youre building a rich, client-side web
application -- not web pages with a few JSdriven features gracefully

When you dont care about degrading

What Backbone Is Not


A collection of UI widgets Rails- or Ruby-specic

The Backbone Universe


A collection is a list of models of a common type. Collections have logic for sorting, ltering, etc., and broadcast events when their contents change. A Backbone model is similar to a Rails model. It wraps a row of data in business logic, and res events when it changes.

Collections

Models

Views are self-contained chunks of UI. Views use models and templates to render themselves, and update models in response to UI events.

Controllers

Views

Templates

A controller binds URL routes to methods (like actions) that render views.

Templates are ERB-style HTML chunks. A view gets data from models and binds it to one or more templates to render itself.

Dependencies & Tools


Dependencies: Underscore.js and either
JQuery or Zepto engine

Recommended: json2 and a templating Jammit for asset packaging -- generally


awesome, but especially handy for template bundling (Rails only)

Some quick examples

Models & Collections


// Define the Todo model var Todo = Backbone.Model.extend({ defaults: { content: 'Empty todo...', done: false }, validate: function(attrs) { if (attrs.content.length > 100) { return "Todo is too long"; } } }); // Define the Todos collection var Todos = Backbone.Collection.extend({ model: Todo, url: '/todos' });

Models & Collections


// Create the collection var todos = new Todos(); // Create a Todo instance var todo = new Todo({ content: "Buy pretzels and slurm" }); // Add the todo to the collection // (event fired!) todos.add(todo); // Save the todo // (event fired!) todo.save();

Dening a View
var TodoView = Backbone.View.extend({ // Listen to events in our associated DOM element events: { "click .check": "toggleDone" }, initialize: function() { // Call our render method when our model changes this.model.bind('change', this.render); }, // When the checkbox is clicked, update the model's done property toggleDone: function() { this.model.set({ done: this.$('.check').is(':checked') }); } });

Resources

Hello Backbone.js (builds up Todos.js a piece at a time) - http://arturadib.github.com/hello-backbonejs/ CloudEdit tutorial (with sample Rails app) - http:// Quiet Clarity (thoughtful piece on app architecture) - http://eetventures.com/2011/02/08/quiet-clarity/ Jammit (asset packaging for Rails) - http://
documentcloud.github.com/jammit/ www.jamesyu.org/2011/01/27/cloudedit-a-backbone-js-tutorial-by-example/

The End

Will post these slides to Twitter @lovitt and the DCRUG Meetup message board tonight If you are looking for a new job, please get in touch (SB Nation is awesome) Thanks for listening

Any questions?

Das könnte Ihnen auch gefallen