在页面加载时不会触发默认路由内的主干pubsub - global事件

Backbone pubsub - global event not triggering inside default route on page load

本文关键字:pubsub 事件 global 路由 默认 加载      更新时间:2023-09-26

我已经用Backbone创建了一个pubSub对象,如下所示:

App.Vent = _.extend({}, Backbone.Events);

我还创建了一个路由器,它在默认uri上触发一个全局事件:http://localhost/

App.Router = Backbone.Router.extend({
    routes: {
        '': 'default',
    },
    default: function() {
        App.Vent.trigger('contactsTable:show');
    }
});
App.Views.ContactsTable = Backbone.View.extend({
    tagName: 'ul',
    initialize: function() {
        App.Vent.on('contactsTable:show', this.updateApp, this);
    },
    updateApp: function() {
        console.log( 'Show All Contacts' );
    }
});
new App.Router;
Backbone.history.start();
new App.Views.ContactsTable;

方法default被成功调用,但是方法内部的事件(contactsTable:show) 没有被触发。

然而,如果我最初在说:http://localhost/#contacts上加载页面,然后从那里导航回http://localhost/,事件确实在路由器方法中被触发。

我不明白为什么会这样。我需要在默认路由上触发一个事件,无论它是否是应用程序打开时的第一条路由。

看起来App.Vent中没有任何内容绑定到'contactsTable:show',请添加以下行并检查是否在控制台中看到消息。

App.Vent.bind("contactsTable:show", function(){
    console.log('Inside - contactsTable:show');
});

回答我自己的问题,我的问题是routerBackbone.history.start()在绑定我的视图中的事件侦听器之前被调用

发生这种情况是因为我的视图(包含侦听器)在AJAX请求的回调函数中被实例化,并且在服务器返回响应之前执行了RouterBackbone.history.start()

这是我现在定义了我的模型,视图集合和路由器后的工作代码:

var contactsCollection = new App.Collections.Contacts();
contactsCollection.fetch().then(function() {
    var contactsTableView = new App.Views.ContactsTable({
        collection: contactsCollection
    });
    new App.Router;
    Backbone.history.start();
});

视图中的监听器现在在初始页面加载时响应事件