【问题标题】:Getting a TypeError: this.options is undefined获取 TypeError:this.options 未定义
【发布时间】:2014-02-12 19:59:11
【问题描述】:

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


【解决方案1】:

尝试这样做:

  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;
    }
  });

【讨论】:

    【解决方案2】:

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

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

    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;
       }
     });
    

    【讨论】:

    • 我试过这个:initialize: function(options) { return this.options = options || {}; },它成功了。
    • 虽然您的观点在纯 JavaScript 中是正确的,但在使用 Backbone 的扩展时并非如此。 Backbone 会将您定义并传递给extend 的函数复制到对象的原型中,因此this 在被调用时将被正确设置为对象的实例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-26
    • 2016-07-31
    • 2019-02-10
    相关资源
    最近更新 更多