Book Image

Backbone.js Patterns and Best Practices

By : Swarnendu De
Book Image

Backbone.js Patterns and Best Practices

By: Swarnendu De

Overview of this book

Table of Contents (19 chapters)
Backbone.js Patterns and Best Practices
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Precompiling Templates on the Server Side
Index

Avoiding memory leaks with the listenTo() method


Memory management is a very important part of any application. Generally, for frontend development, developers do not bother much about memory leaks; however, this doesn't hold true when we develop single page frontend-heavy applications. These types of applications deal with many frontend components and the lowest number of page refreshes, which can create several opportunities for memory leaks. While developing such applications, we should always be careful to clean up events when an object is destroyed. To understand this with an example, assume we have a view that displays its model's data. The render() method of the view is called whenever the change event is fired on that model:

// Memory leak
var MyView = Backbone.View.extend({
  tpl: '<%= name %>',
  model: new Backbone.Model({
    name: 'Suramya'
  }),

  initialize: function () {
    this.model.on('change', this.render, this);
  },

  render: function () {
    var html = _.template...