0

How does listenTo / stopListening work with respect to on / off?

In the console, I'm experimenting with the Backbone event system as such ...

// works
Backbone.on('x', function(){console.log('x happened');})

// works
Backbone.trigger('x');

// works
Backbone.off('x');

// works
Backbone.once('x', function(){console.log('x happened');})

I'm trying to extend my example to use listenTo() and stopListening().

These are listed as the inversion of control types. Is there a simple way to show there use as above?

The primary difference, as viewed from the source, is that the first parameter needs to be an object.

2 Answers2

1

It is exactly the same, except it's an inversion of control: listenTo binds the events on the listening object, rather than the triggering object. This is most useful for cleaning up View event handlers, because the view now knows which events it's listening to and can unbind them when it's removed. With the original system, only the triggering object (ie, the model) would have direct knowledge of the bound events.

There's a good explanation of the concept here. It shows how people used to do it before it was added to Backbone.

In your example, you don't really have a "listening" object, since your handler is just an anonymous function. But it would be something like obj.listenTo(Backbone, "x", obj.alert);, where alert would be a handler method on obj.

Community
  • 1
  • 1
Andrew Kirkegaard
  • 1,676
  • 11
  • 13
0

Because listenTo and stopListening work on a different object you need to create another object that has access to the event system. One easy way is to create a view object as such.

var View1 = new Backbone.View();

Next setup a listener:

Backbone.listenTo(View1, 'x', function(){console.log('I heard x');});

Now trigger the event on View1

View1.trigger('x');

Finally remove the listener

Backbone.stopListening(View1,'x');

That covers the 6 main methods of the event system.

Tested and working...