Backbone Marionette Event Aggregator : how to listen at the App level to ItemView Event

僤鯓⒐⒋嵵緔 提交于 2019-12-05 11:42:28

If you want to listen for the event at the application level, you have to trigger it at the application level:

displayMessage: function () {
  myApp.trigger('display:message');
}

Assuming myApp is your Marionette application. Then, you simply listen for that event:

myApp.on('display:message', ...)

It's the only way to implement what you asked for: "I have an ItemView which trigger an event, and I would like to receive this event at the application level". Depending on your situation, the better way is to either

Neither of these 2 solutions requires "polluting" the global event space.

ok so I tried the listenTo solution, here is part of my code:

var regionManager = Backbone.Marionette.Region.extend({
    el: "#messages",
    onShow: function (view) {
        this.listenTo(view, "display:message", this.displayMessage);
    },
    displayMessage: function () {
        console.log('regionManager received display:message');
    }
});
App.addRegions({
    messageListRegion: regionManager

});
var MessageItemView = Backbone.Marionette.ItemView.extend({
    template: "#messagesTPL",
    tagName: 'tr',
    className: 'messageItem',
    events : {
        'click': 'displayMessage'
    },
    displayMessage: function (e) {
        e.preventDefault();
        e.stopPropagation();
        this.trigger('display:message');
    }
});

But when I click on a messageItemView, the regionManager does not execute the displayMessage callback set in the listenTo method.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!