Backbone Cannot read property 'property' of undefined error in backbone view
backbone-views, backbone.js, javascript
Solution
Backbone views used to automatically copy the constructor options to `this.options` but no longer:
Change Log 1.1.0 — Oct. 10, 2013
- Backbone Views no longer automatically attach options passed to the constructor as `this.options`, but you can do it yourself if you prefer.
So if you're depending on `this.options` being set in your views then you'll have to do it yourself:
var MenuItemDetails = Backbone.View.extend({
initialize: function(options) {
this.options = options;
},
//...
});
Or better, unpack the options so that you know what your view's interface is:
initialize: function(options) {
this.options = _(options).pick('name', 'category', 'imagepath');
}
This way you at least have a list of what you're expecting to see in `options`.
Problem
I've just decided to learn backbone. I'm following a video tutorial. Everything works fine there, but at my end I get this error "Uncaught TypeError: Cannot read property 'name' of undefined". Here's my code: ``` var MenuItemDetails = Backbone.View.extend({ render: function() { var markup = this.options.name + this.options.category + this.options.imagepath; // I also had some html markup in the string above, of course, but I've striped it because stackoverflow didn't show it in the preview of my post. this.$el.html(markup); return this; } }); var AppRouter = Backbone.Router.extend({ routes: { "" : "list", "menu-items/new" : "itemForm", "menu-items/:item" : "itemDetails" }, list: function() { $('#app').html('List screen'); }, itemDetails: function(item) { var view = new MenuItemDetails({ name: item, category: 'Some category', imagepath: 'no-image.jpg' }); $('#app').html(view.render().el); }, itemForm: function() { $('#app').html('New item form'); } }); var app = new AppRouter(); $(function() { Backbone.history.start(); }); ``` The "itemDetails" function gives "Uncaught TypeError: Cannot read property 'name' of undefined" error. Of course, if I don't use the 'name' property in the view, I get "Uncaught TypeError: Cannot read property 'category' of undefined". In the video tutorial that I'm following, everything works fine (it uses version 0.9.1 of backbonejs). I use the latest (1.1.0). Does anybody know why do I get this error? There isn't anything misspelled, everything is in the right order (exactly as in the video tutorial, where it works). Why does backbone throws me this error?