Question

So I've managed to figure out how to populate my collection from an external file, and render a view based on a url, but I'm running into a problem. The code below is working as intended, except on page load, I'm getting the following error:

Uncaught TypeError: Cannot call method 'get' of undefined 

Getting rid of "view.render()" eliminates the error, but now the app no longer responds to ID changes in the url (e.g. going from #/donuts/1 to #/donuts/2 does not update the view)

Could someone point me in the right direction here?

The Code:

(function(){
var Donut = Backbone.Model.extend({
    defaults: {
        name: null,
        sprinkles: null,
        cream_filled: null
    }
});
var Donuts = Backbone.Collection.extend({
    url: 'json.json',
    model: Donut,
    initialize: function() {
        this.fetch();
    }
})

var donuts = new Donuts();

var donutView = Backbone.View.extend({
     initialize: function() {
        this.collection.bind("reset", this.render, this)
    }, 
    render: function() {
        console.log(this.collection.models[this.id].get('name'))
    }
});

var App = Backbone.Router.extend({
    routes: {
        "donut/:id" : 'donutName',
    },

    donutName: function(id) {
        var view = new donutView({
            collection: donuts,
            id: id
        });
        view.render();

    }
});

var app = new App();
Backbone.history.start();
})(jQuery);

The JSON:

[
    {
        "name": "Boston Cream",
        "sprinkles" : "false",
        "cream_filled": "true"
    },
    {
        "name": "Plain",
        "sprinkles": "false",
        "cream_filled": "false"
    },
    {
        "name": "Sprinkles",
        "sprinkles": "true",
        "cream_filled": "false"
    }
]
Was it helpful?

Solution

Looks like a bit of a flow issue here. You have the view listening to the collection's "reset" event. So when there's a reset, the view will render. That is just fine. But I believe the problem is in your router. When you route, you're creating a new instance of the view, but not doing anything with the collection, so its state is the same.

Since you're already observing the collection, do nothing with the view. When you route, update the collection's url, then do a fetch. This will trigger a reset and the view should then update itself.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top