Home >Web Front-end >JS Tutorial >Backbone.js Basics: Bringing an App to Life with Events
This article explores Backbone.js, a JavaScript framework employing an MV* architecture for building applications. It focuses on event handling, a crucial aspect of separating concerns between views and models.
Key Concepts:
The tutorial builds upon a previous lesson, introducing controller-like logic to handle user interactions. It emphasizes the importance of separating concerns: views handle presentation and user input, while models manage data logic.
Event Handling Techniques:
The article details two primary methods for handling events in Backbone.js:
events
Hash: This approach directly defines event handlers within the view using a key-value map. The key specifies the event and target element (e.g., 'click .add-one': 'addOne'
), and the value is the function to execute.
listenTo
Method: This method allows an object (typically a view) to listen for events on another object (typically a model). It's particularly useful for managing event listeners and ensuring they're properly cleaned up. The example uses this.listenTo(this.model, "change", this.render);
to re-render the view whenever the model changes.
The tutorial provides a practical example of adding and subtracting stock from a surfboard inventory app. It demonstrates how to:
addOne
, minusOne
) that update the model.addOne
, minusOne
) to modify data and trigger the "change"
event.initialize
function in the view to listen for the model's "change"
event and re-render the view.The article concludes with a CodePen demo and a FAQ section addressing common questions about Backbone.js events, including using on
, off
, once
, stopListening
, and handling events on specific model attributes or collections. A call to action promotes a SitePoint Premium course on Backbone.js.
The above is the detailed content of Backbone.js Basics: Bringing an App to Life with Events. For more information, please follow other related articles on the PHP Chinese website!