Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone 0.9.9: Difference between listenTo and on

I am trying to learn the new changes they did in Backbone 0.9.9.

Currently I got problems to understand the difference between listenTo and on:

listenTo

var View = Backbone.View.extend({      tagName: "div",      intialize: function() {         this.listenTo(this.model, 'change', this.render);     },      render: function() {         this.$el.empty();         this.$el.append('<p>hello world</p>');     }  }); 

on

var View = Backbone.View.extend({      tagName: "div",      intialize: function() {         this.model.on('change', this.render, this);     },      render: function() {         this.$el.empty();         this.$el.append('<p>hello world</p>');     }  }); 

I have heard that listenTo allows with stopListening to unsubscribe from all events when for example the view gets removed to avoid memory leaks.

Is this the only reason?

like image 987
bodokaiser Avatar asked Dec 26 '12 13:12

bodokaiser


People also ask

Is Backbone JS still used?

Backbone. Backbone has been around for a long time, but it's still under steady and regular development. It's a good choice if you want a flexible JavaScript framework with a simple model for representing data and getting it into views.

What is backbone JS used for?

BackboneJS allows developing of applications and the frontend in a much easier way by using JavaScript functions. BackboneJS provides various building blocks such as models, views, events, routers and collections for assembling the client side web applications.

What is the significance of edge version of BackboneJS?

Designed for developing single-page web apps and for maintaining various parts of web applications synchronized.

Is backbone a MVC?

Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).


1 Answers

When you create a view, both listenTo and on add event handling. However, when the view is destroyed, the listenTo call will automatically remove the event handler. This prevents memory leaks and zombie event listeners.

So, use on if you want to manage the handler yourself. Just make sure to call off. Otherwise, call listenTo.

like image 66
Richard Avatar answered Sep 21 '22 14:09

Richard