Owen
Owen

Reputation: 1662

Event listener callback does not fire via a normal function call

I'm sure there's a reasonable explanation for this, but I cannot figure it out - a bit of guidance would be much appreciated.

I have the following code using Backbone:

var ExampleCollection = Backbone.Collection.extend({
    exampleEvent: function() {console.log('event fired')}
});

var ExampleView = Backbone.View.extend({
    el:'body',
    onExampleEvent: function() {console.log('listener heard it')},
    initialize: function() {
        this.listenTo(this.collection,'exampleEvent',this.onExampleEvent);
    }
});

var testCollection = new ExampleCollection;
var testView = new ExampleView({collection:testCollection});

In the console, when I enter the command testCollection.trigger('exampleEvent') the onExampleEvent callback function fires . however, when I enter the command testCollection.exampleEvent() the exampleEvent function fires but the onExampleEvent callback function doesn't.

If anyone could explain to my why this happens I would appreciate it as I have been looking for a while and can't figure it out.

Many thanks in advance.

Upvotes: 1

Views: 192

Answers (1)

Radosław Miernik
Radosław Miernik

Reputation: 4094

Just think about it - when You call

 testCollection.exampleEvent()

You just execute it, and... Nothing. When

 testCollection.trigger('exampleEvent')

is called, it execute function and every listener.

Upvotes: 1

Related Questions