获取TypeError:this.options未定义

时间:2014-02-12 19:59:11

标签: javascript backbone.js

我正在尝试学习BackboneJS,这是我得到的错误。

我在coffeescript中编码,这是生成的JS我不知道为什么会发生这种情况,因为我认为我正确地做到了。

(function() {
  var AppRouter, MenuItemDetails, app;

  MenuItemDetails = Backbone.View.extend({
    render: function() {
      var markup;
      markup = "<div>" + this.options.category + "</div>";
      this.$el.html(markup);
      return this;
    }
  });

  AppRouter = Backbone.Router.extend({
    routes: {
      "": "list",
      "menu-items/new": "itemForm",
      "menu-items/:item": "itemDetails"
    },
    list: function() {
      return $('#app').html('List Screen');
    },
    itemDetails: function(item) {
      var view;
      view = new MenuItemDetails({
        name: item,
        category: 'Entree',
        imagepath: 'no-image.jpg'
      });
      return $('#app').html(view.render().el);
    },
    itemForm: function() {
      return $('#app').html("New item form");
    }
  });

  app = new AppRouter();

  Backbone.history.start();

}).call(this);

/*
//@ sourceMappingURL=app.map
*/

我哪里错了?

2 个答案:

答案 0 :(得分:0)

尝试这样做:

  MenuItemDetails = Backbone.View.extend({
    initialize: function(options) {
      this.options = options;
    },
    render: function() {
      var markup;
      markup = "<div>" + this.options.category + "</div>";
      this.$el.html(markup);
      return this;
    }
  });

答案 1 :(得分:-1)

您错误地使用了this关键字。

MenuItemDetails = Backbone.View.extend({
render: function() {
  var markup;
  markup = "<div>" + this.options.category + "</div>"; // Error
  this.$el.html(markup);
  return this;
 }
});

这指向不包含属性选项的范围。 Yous应该做这样的事情

 var self = this;
 MenuItemDetails = Backbone.View.extend({
    render: function() {
        var markup;
        markup = "<div>" + self.options.category + "</div>"; // Error
        this.$el.html(markup);
       return this;
   }
 });