Beruflich Dokumente
Kultur Dokumente
js
Event-driven MVC for complex JavaScript web applications
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?
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)
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
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.
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?