Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Mastering Backbone.js

You're reading from   Mastering Backbone.js Design and build scalable web applications using Backbone.js

Arrow left icon
Product type Paperback
Published in Jan 2016
Publisher Packt
ISBN-13 9781783288496
Length 278 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Abiee Echamea Abiee Echamea
Author Profile Icon Abiee Echamea
Abiee Echamea
Arrow right icon
View More author details
Toc

Table of Contents (12) Chapters Close

Preface 1. Architecture of a Backbone application 2. Managing Views FREE CHAPTER 3. Model Bindings 4. Modular Code 5. Dealing with Files 6. Store data in the Browser 7. Build Like a Pro 8. Testing Backbone Applications 9. Deploying to Production 10. Authentication Index

ModelView


The simplest implementation is to render a single model; it's a very straightforward algorithm. Extract data from the model and use a template engine to make the actual render with the data; finally, attach the result in the DOM:

class MyView extends Backbone.View {
  constructor(options) {
    super(options);
    template: _.template($("#my-template").html());
  }
  
  render() {
       var data = this.model.toJSON();
    var renderedHtml = this.template(data);
    this.$el.html(renderedHtml);
    return this;
  }
}

In the following code we can identify five steps to rendering the view.

  1. Get the template:

    $("#my-template").html()
    
  2. Compile the template:

    _.template($("#my-template").html())
    
  3. Get data from the model:

    var data = this.model.toJSON()
    
  4. Render the template with model data:

    renderedHtml = this.template(data)
    
  5. Put the result on the DOM:

    this.$el.html(renderedHtml)
    

Note that we return this in the render() method; this is useful for chaining calls. These steps are common for all...

You have been reading a chapter from
Mastering Backbone.js
Published in: Jan 2016
Publisher: Packt
ISBN-13: 9781783288496
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime
Banner background image