事件侦听器回调不会通过正常的函数调用触发

Event listener callback does not fire via a normal function call

本文关键字:函数调用 回调 侦听器 事件      更新时间:2023-09-26

我相信对此有合理的解释,但我无法理解——如果能提供一些指导,我将不胜感激。

我使用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});

在控制台中,当我输入命令testCollection.trigger('exampleEvent')时,onExampleEvent回调函数将启动。然而,当我输入命令testCollection.exampleEvent()时,exampleEvent函数会激发,但onExampleEvent回调函数不会。

如果有人能向我解释为什么会发生这种情况,我会很感激,因为我已经找了一段时间了,但一直想不通。

非常感谢。

想想吧——当你调用时

 testCollection.exampleEvent()

你只要执行它,然后。。。没有什么当

 testCollection.trigger('exampleEvent')

被调用时,它执行函数和每个侦听器。