Book Image

Backbone.js Essentials

By : Jeremy Walker
Book Image

Backbone.js Essentials

By: Jeremy Walker

Overview of this book

<p>This book offers insight into creating and maintaining dynamic Backbone.js web applications. It delves into the the fundamentals of Backbone.js and helps you achieve mastery of the Backbone library.</p> <p>Starting with Models and Collections, you'll learn how to simplify client-side data management and easily transmit data to and from your server. Next, you'll learn to use Views and Routers to facilitate DOM manipulation and URL control so that your visitors can navigate your entire site without ever leaving the first HTML page. Finally, you'll learn how to combine those building blocks with other tools to achieve high-performance, testable, and maintainable web applications.</p>
Table of Contents (20 chapters)
Backbone.js Essentials
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Handling events


While the Views we've described so far are great for creating and/or wrapping existing HTML elements, they're not very good at responding when a user interacts with them. One approach to solve this problem will be to hook up event handlers inside a View's initialize method, as follows:

var FormView = Backbone.View.extend({
    id: 'clickableForm',
    initialize: function() {
        this.$el.on('click', _.bind(this.handleClick, this));
    },
    handleClick: function() {
        alert('You clicked on ' + this.id + '!');
    }
});
var $form = new FormView().$el;
$form.click(); // alerts "You clicked on clickableForm!"

However, there are two problems with this approach, as follows:

  • It's not terribly readable

  • We have to bind the event handler when we create it so that we can still reference this from inside it

Luckily, Backbone offers a better way, in the form of an optional property called events. We can use this events property to simplify our previous example:

var FormView =...