55

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?

Emile Bergeron
  • 17,074
  • 5
  • 83
  • 129
bodokaiser
  • 15,122
  • 22
  • 97
  • 140
  • Possible duplicate of [Backbone js .listenTo vs .on](https://stackoverflow.com/questions/16823746/backbone-js-listento-vs-on) – Emile Bergeron Dec 11 '17 at 05:22

2 Answers2

53

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.

Richard
  • 6,215
  • 4
  • 33
  • 48
40

listenTo and stopListening came from the community, basically. They help to make it easier to bind and unbind events.

There's a lot of existing documentation and blog posts surrounding the idea, including stuff that I've written on the subject.

Johnny Oshika is the first person that I saw using this technique. It was originally posted as an answer to a StackOverflow question here: Backbone.js : repopulate or recreate the view?

You can read what I've written about this, here:

Community
  • 1
  • 1
Derick Bailey
  • 72,004
  • 22
  • 206
  • 219
  • I am just learning about this too, so this is a timely question for me. Is the recommended practice to now use listenTo for binding all events that may need to be unbound at some point during the lifecycle of the app? – user1031947 Dec 26 '12 at 18:36
  • 12
    It's a good question that would be good to have a straighter answer to – ErichBSchulz Mar 02 '13 at 13:13
  • @ErichBSchulz agreed, though there is no reference to listenTo in the 3 blog posts hs has made, I guess @DerickBailey is saying yes, use `listenTo` over `on`. – AJP Apr 13 '13 at 13:22
  • 3
    see this, more recent post: http://lostechies.com/derickbailey/2013/02/06/managing-events-as-relationships-not-just-references/ – Derick Bailey Apr 13 '13 at 13:51