Nyxynyx
Nyxynyx

Reputation: 63619

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

Hi I have a Collection which uses fetch() to do the initial fetch from the API. On a user's interaction, a second fetch is triggered, but instead of using the original fetch(), I used a fetchNew() that I defined myself:

Collection

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

This will add only the new Models to the collection, and render only the Views of these new Models. (if all the Views are removed and re-rendered, it will cause a flicker)

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

});

Error

However I am getting an error:

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

which corresponds to this line in ListingMarkerView

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

Debug

If I were to place a console.log(item) before the line that renders ListingMarkerView

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

I do see a valid item:

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

So...

Question

What seems to be the problem? How can this be solved? Thank you!

Upvotes: 3

Views: 9656

Answers (1)

blockhead
blockhead

Reputation: 9705

The problem is render does not have this defined correctly. Add a initialize method in the view class like this:

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

Upvotes: 6

Related Questions