0
votes

I'm trying to include an optional argument in my Backbone view's render function, like this:

var AppView = Backbone.View.extend({
        el: '#app',

        initialize: function(){
                _.bindAll(this,'render');
                this.listenTo(app.collection.sellables,'reset', this.render);
        },

        render: function(sellableId){
                if(typeof sellableId == "undefined"){
                        var sellable = app.collection.sellables.first();
                }
                else{
                        var sellable = app.collection.sellables.get(sellableId);
                }
                var view = new SellableView({model: sellable});
                this.$('#sellables').append(view.render().el);
        },
});

The first time this view renders, it occurs because the app.collection.sellables collection gets reset after receiving some data from the server. When this reset occurs, the view's render function gets called, but instead of being called with sellableId as undefined, the sellableId is equal to the app.collection.sellables variable, which is causing errors. To clarify, the view's render function is being called because of this:

app.collection.sellables.reset(data.skus);

Why would my render function be receiving the collection as an argument rather than the argument being undefined?

Also, if I render the view manually, it works correctly and the sellableId argument is undefined as expected:

var app.view.app = new AppView;
app.view.app.render();
1

1 Answers

0
votes

You're binding your render to "reset" right here:

this.listenTo(app.collection.sellables,'reset', this.render);

From the Catalog of Events:

  • "reset" (collection, options) — when the collection's entire contents have been replaced.

So a handler for a "reset" event always gets the collection as its first argument. Keep in mind that a JavaScript function's arguments are determined when the function is called, not when the function is defined.

You have a few options. You could bind something else to the "reset" event:

initialize: function() {
    //...
    this.listenTo(app.collection.sellables, 'reset', this.been_reset);
},
been_reset: function() {
    this.render();
}

You could leave render without arguments (like a standard render) and have a separate function to handle the arguments:

render: function() {
    return this.append_model(app.collection.sellables.first());
},
append_model: function(sellable) {
    var view = new SellableView({model: sellable});
    this.$('#sellables').append(view.render().el);
    return this;
}

Then you'd call view.append_model(app.collection.sellables.get(sellableId)) to add a specific model.