Skip to content

Instantly share code, notes, and snippets.

@EndangeredMassa
Created October 23, 2012 14:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save EndangeredMassa/50bdc776523c5b72a96f to your computer and use it in GitHub Desktop.
Save EndangeredMassa/50bdc776523c5b72a96f to your computer and use it in GitHub Desktop.
Intro to Backbone.js

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

_

_

_

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment