Reputation: 640
Is there any way to catch and handle reference errors in Backbone view? For an example, broken collection crashing my view (render method never fires), also navigation links in my header view no more works:
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();
Upvotes: 0
Views: 94
Reputation: 18869
I would say no because:
The example you provide shows a compile error; View
will never be created because BadCollection
was never declared.
Logically, there shouldn't be a way to circumvent this error, other than to adapt the code for the compiler to understand, ie. defining the BadCollection object.
One way of solving this problem from the pov of the View
could be by setting the collection dynamically on the view:
var view = new View({ collection: new BadCollection});
Now you have a way to intercept runtime errors in the View object by checking if the collection was defined in the initialize method and throwing an error that you can handle when instantiating the 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/
Upvotes: 2