1

楷模

Network.Models.FeedItem = Backbone.Model.extend({
  isPost: function() {
    return this.get('template') === 'post';
  }
})

Network.Models.Post = Backbone.Model.extend({
  urlRoot: '/p',

  hasImageInDetails: function() {
    if(this.get('details').match(/<img[^<]*>[\w\d]*<\/img>|<img[^\/]*\/>/i)) {
      return true
    }
  }
)}

模板 feed_items/post.jst.eco

  <% if @model.hasImageInDetails(): %>
    has image
  <% end %>

意见

Network.Views.FeedItemView = Backbone.View.extend({
  initialize: function() {
    var self = this;
    this.template = JST[this.path()];
  },

  render: function() {
    var self = this;
    $(this.el).html(this.template({ model: this.model }));

    if (this.model.isPost()) {
      this.questionView = new Network.Views.FeedItems.Post({
        model: this.model,
        el: this.$el,
        parent: this
      });
    }
  }
});

Network.Views.FeedItems.Post = Backbone.View.extend({
  initialize: function() {
    this.render();
  },

  render: function() {
    var self = this;
  }
});

但我收到一个错误:

Uncaught TypeError: Object [object Object] has no method 'hasImageInDetails' 
4

1 回答 1

0

从您的代码看来,您希望FeedItemView处理类型的模型FeedItem,因为您调用了一个方法model.isPost(),该方法在FeedItem. 模型上定义了 Eco 找不到的方法Post,因此从逻辑上讲,其中一个会失败。

你的意思是Post从延伸FeedItem?在这种情况下,而不是:

Network.Models.Post = Backbone.Model.extend({ ... });

您应该这样声明模型:

Network.Models.Post = Network.Models.FeedItem.extend({ ... });
于 2013-01-08T17:17:26.007 回答