【问题标题】:Backbone.js: Uncaught TypeError: Object #<Object> has no method 'get'Backbone.js:未捕获的类型错误:对象 #<Object> 没有方法 'get'
【发布时间】:2012-09-29 18:27:00
【问题描述】:

您好,我有一个 Collection,它使用 fetch() 从 API 进行初始提取。在用户交互时,触发了第二次提取,但我没有使用原始的fetch(),而是使用了我自己定义的fetchNew()

收藏

ListingCollection = Backbone.Collection.extend({
    model: Listing,
    url: '/api/search_by_bounds',

    fetchNew: function(options) {
        options = options || {};
        var collection = this,
            success = options.success;
        options.success = function(resp, status, xhr) {
            _(collection.parse(resp, xhr)).each(function(item) {
                // added this conditional block
                if (!collection.get(item.id)) {
                    // Update collection
                    collection.add(item, {silent:true});
                    // Render View
                    new ListingMarkerView({ model:item }).render();
                }
            });
            if (!options.silent) {
                collection.trigger('reset', collection, options);
            }
            if (success) success(collection, resp);
        };
        return (this.sync || Backbone.sync).call(this, 'read', this, options);
    }
});

这只会将新模型添加到集合中,并仅渲染这些新模型的视图。 (如果所有的View都被移除并重新渲染,会导致闪烁)

查看

ListingMarkerView = Backbone.View.extend({

    render: function() {
        var marker = L.marker([this.model.get('lat'), this.model.get('lng')]);
        markers.addLayer(marker);
    },

    close: function() {
        this.unbind;
    }

});

错误

但是我得到一个错误:

Uncaught TypeError: Object #<Object> has no method 'get' 

对应ListingMarkerView中的这一行

var marker = L.marker([this.model.get('lat'), this.model.get('lng')]);

调试

如果我要在呈现ListingMarkerView 的行之前放置一个console.log(item)

console.log(item)
new ListingMarkerView({ model:item }).render();

我确实看到了一个有效的item

Object
    id: "2599084"
    lat: "42.276852"
    lng: "-71.165421"
    price: "2850"
    __proto__: Object

所以...

问题

似乎是什么问题?如何解决?谢谢!

【问题讨论】:

  • 我宁愿用平常的.reset,你为什么要这样做?您可以发布工作站点的链接以便我进行检查吗?
  • .reset 是否会删除初始 fetch() 中但未在后续调用中的项目?我希望只是将新模型添加到集合中而不删除旧模型。
  • 如果您想添加新的而不删除旧的,请使用fetch({add:true})。但是,您仍然应该理解我对您的问题给出的答案,因为它肯定会在其他地方出现。
  • 是的fetch{add:true})有我想要的效果,谢谢!但是,使用_.bindAll 后我仍然无法渲染视图
  • 再次:您能否发布工作站点的链接以便我进行检查?

标签: javascript jquery backbone.js


【解决方案1】:

问题是渲染没有正确定义this。 在视图类中添加initialize 方法,如下所示:

initialize: function() {
   _.bindAll(this); //Make all methods in this class have `this` bound to this class
}

【讨论】:

  • 我添加了_.bindAll(this, 'render', 'close');,但得到了同样的错误
  • this.model 等于什么?
  • 现在很好用!使用add:true 并将渲染更改为触发add 而不是reset,这对我来说听起来很奇怪
  • 简单有用的答案。谢谢。
  • 请不要按原样使用这个答案......这被认为是不好的做法,正在被弃用并从下划线中删除。
猜你喜欢
  • 2014-01-08
  • 2013-04-19
  • 2012-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多