secret
Last active

Intro to Backbone.js

  • Download Gist
deck.md
Markdown

Sean Massa

@endangeredmassa

Chicago Node.js Meetup

Backbone.js

http://backbonejs.org

Problem: Single-page apps are messy

Breakdown

pirate

Views

var EmailView = Backbone.View.extend({
  tagName: 'div',
  className: 'email',
  template: '{{ from }}: {{ subject }}',
  render: function(){
    var html = Mustache.render(
      this.template,
      this.model.attributes
    );
    this.$el.html(html);
  }
});

View Events

var EmailView = Backbone.View.extend({
  initialize: function(){
    this.model.on('change', this.render, this);
    this.messageBus.on('delete:all', this.remove, this);
  },
  events: {
    'click': 'expand'
  },
  expand: function(){
    this.trigger('show:email', this);
  }
});

Models

var model = new Backbone.Model();
model.set('from', 'someguy@gmail.com');
var description = model.get('description');
model.attributes;
model.on('change', function(){}, this);

var EmailModel = Backbone.Model.extend({
  url: '/email'
});

var email = new EmailModel({id: 3});
emailModel.fetch();
emailModel.save();

Collections

var collection = new Backbone.Collection();
collection.add(someModel);
collection.remove(someModel);
collection.reset([model1, model2]);
collection.models;
collection.each(function(model){});

var EmailCollection = Backbone.Collection.extend({
  url: '/emails'
});

var emails = new EmailCollection();
emails.fetch();

Routers

var Router = Backbone.Router.extend({
  routes: {
    '': 'index',
    '/emails': 'emailIndex'
  },
  index: function(){
    window.router.navigate('/emails', true);
  },
  emailIndex: function(){
    var emailsView = new EmailCollectionView();
    emailsView.render();
    $('#container').append(emailView.el);
  }
});
window.router = new Router;
Backbone.history.start({pushState: true});

Large Example

http://backbonejs.org/#examples

http://my.cl.ly

http://cloudapp.github.com/engine

Best Practices

  • Keep views self-contained
  • Communicate up by emitting events
  • Communicate out with an event bus
  • Communicate down with your references
  • Not everything has to be a Backbone module

Thanks!

@endangeredmassa

_

_

_

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.