简体   繁体   English

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

[英]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: 我有以下使用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 . 在控制台中,当我输入命令testCollection.trigger('exampleEvent')onExampleEvent回调函数将触发。 however, when I enter the command testCollection.exampleEvent() the exampleEvent function fires but the onExampleEvent callback function doesn't. 然而,当我输入命令testCollection.exampleEvent()exampleEvent功能火灾,但onExampleEvent回调函数没有。

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. 提前谢谢了。

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. 被调用,它执行函数和每个侦听器。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM