Book Image

Backbone.js Blueprints

By : Andrew Burgess
Book Image

Backbone.js Blueprints

By: Andrew Burgess

Overview of this book

<p>Backbone.js is an open source, JavaScript library that helps you to build sophisticated and structured web apps. It's important to have well-organized frontend code for easy maintenance and extendability. With the Backbone framework, you'll be able to build applications that are a breeze to manage.<br /><br />In this book, you will discover how to build seven complete web applications from scratch. You'll learn how to use all the components of the Backbone framework individually, and how to use them together to create fully featured applications. In addition, you'll also learn how Backbone thinks so you can leverage it to write the most efficient frontend JavaScript code.<br /><br />Through this book, you will learn to write good server-side JavaScript to support your frontend applications. This easy-to-follow guide is packed with projects, code, and solid explanations that will give you the confidence to write your own web applications from scratch.</p>
Table of Contents (14 chapters)
Backbone.js Blueprints
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Writing the tokens view


Now that we have the models more or less in place, we're ready to start writing the actual views. Let's start with something simple: the tokens. We start with the TokensView class:

var TokensView = Backbone.View.extend({
  render: function () {
    this.collection.tokens()
      .shuffle().forEach(this.addToken, this);
    return this;
  },
  addToken: function (token) {
    this.el.appendChild(new TokenView({ 
      model: token 
    }).render().el);
  }
});

Writing this class is very simple. We get the collection of tokens from the game, call the built-in shuffle method to shuffle the tokens, and then render them each with the addToken method. This method renders a TokenView instance and appends it to the element. So that's the next stop—the TokenView class:

var TokenView = Backbone.View.extend({
  className: 'token',
  events: {
    'click': 'choose'
  },
  render: function () {
    this.model.view = this;
    this.el.innerHTML = this.model.get('text');
    return...