Backbone Marionette - Uncaught TypeError:无法调用未定义的方法'show'

时间:2013-07-10 13:46:54

标签: marionette

我知道错误是由jQuery生成的。有没有什么办法可以构建一个backbone.marionette应用程序以避免以下错误?

Uncaught TypeError: Cannot call method 'show' of undefined

发生错误是因为我创建了一个包含区域的布局。在onRender函数中,我加载一个集合并执行fetch。提取完成后,我填充该区域。如果我切换到另一个视图,则由于self.content.show不再存在而触发错误。

var view = Marionette.Layout.extend({
    template: _.template(tplPage),
    className: 'customers-view',
    regions:{
        content: '.customers-content'
    },

    onRender: function(){
        var self = this,
            colCustomers = new ColCustomers();

        colCustomers.fetch({success: function(){
            self.content.show(new ViewCustomersList({collection: colCustomers}));
        }});
    }
});

注意:目前我在一个try catch中包含self.content.show()并且它正在工作。理想情况下,我避免这样做。

1 个答案:

答案 0 :(得分:1)

修改onRender函数并以不同方式监听提取。

onRender: function(){
  var colCustomers = new ColCustomers();
  this.listenTo(colCustomers, "sync", function () {
    this.content.show(new ViewCustomersList({collection: colCustomers}));
  });
  colCustomers.fetch();
}

我所做的是改变绑定事件监听器的方法。通过使用Backbone.Events中的listenTo函数,您可以获得在侦听器对象死亡时免费清理的处理程序。