Backbone.js:未捕获TypeError:对象#<Object>没有方法'get'

Nyx*_*nyx 3 javascript jquery backbone.js

嗨,我有一个用于fetch()从API进行初始提取的Collection .在用户的交互中,第二次获取被触发,但是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);
    }
});
Run Code Online (Sandbox Code Playgroud)

这将仅将新模型添加到集合中,并仅渲染这些新模型的视图.(如果删除并重新渲染所有视图,则会导致闪烁)

视图

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

});
Run Code Online (Sandbox Code Playgroud)

错误

但是我收到一个错误:

Uncaught TypeError: Object #<Object> has no method 'get' 
Run Code Online (Sandbox Code Playgroud)

对应于这一行 ListingMarkerView

var marker = L.marker([this.model.get('lat'), this.model.get('lng')]);
Run Code Online (Sandbox Code Playgroud)

调试

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

console.log(item)
new ListingMarkerView({ model:item }).render();
Run Code Online (Sandbox Code Playgroud)

我看到有效的item:

Object
    id: "2599084"
    lat: "42.276852"
    lng: "-71.165421"
    price: "2850"
    __proto__: Object
Run Code Online (Sandbox Code Playgroud)

所以...

什么似乎是问题?怎么解决这个问题?谢谢!

blo*_*ead 6

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

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