在 Backbone.View 中捕获引用错误

Catch reference errors in Backbone.View

有什么方法可以捕获和处理 Backbone 视图中的引用错误吗?例如,损坏的 collection 使我的视图崩溃(渲染方法永远不会触发),我的 header 视图中的导航链接也不再有效:

var View = Backbone.View.extend({
   //Uncaught ReferenceError: BadCollection is not defined 
   collection: new BadCollection(),
   render: function() {
     //Render never fires
     this.$el.html(_.template(tmpl)());
   }
})

return new View();

我会说不,因为:
您提供的示例显示编译错误; View 将永远不会被创建,因为 BadCollection 从未被声明过。
从逻辑上讲,应该没有办法避免这个错误,除了调整编译器理解的代码,即。定义 BadCollection 对象。

View 的视角解决此问题的一种方法是在视图上动态设置集合:

var view = new View({ collection: new BadCollection}); 

现在您可以通过检查集合是否在初始化方法中定义并抛出一个您可以在实例化视图时处理的错误来拦截 View 对象中的运行时错误:

var View = Backbone.View.extend({
    initialize: function(options){ 

        if(!(options.collection instanceof Backbone.Collection)){ 
            console.log("test"); 
            throw new Error("No Backbone Collection spotted!"); 
        }
    }
}); 

try { 
    var view = new View({ collection: "this is just a string"});  
}
catch(err) {
    console.log(err); 
}; 

http://jsfiddle.net/C9wew/7303/