正在获取TypeError:this.options未定义

问题描述 投票:2回答:2

我正在尝试学习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
*/

我要去哪里错了?

javascript backbone.js
2个回答
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
投票

您使用的this关键字错误。

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

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

 var self = this;
 MenuItemDetails = Backbone.View.extend({
    render: function() {
        var markup;
        markup = "<div>" + self.options.category + "</div>"; // Error
        this.$el.html(markup);
       return this;
   }
 });
© www.soinside.com 2019 - 2024. All rights reserved.