Sjaak Rusma
Sjaak Rusma

Reputation: 1434

Dynamically set property of View in BackboneJS

App.Views.WidgetAvailable = Backbone.View.extend({
        tagName: 'li',

        className: 'widget',

        template: template('available_template'),

        render: function(){
            this.$el.html(this.template(this.model.toJSON()));
            return this;
        }
    });

So I got this view which is used by two collections, the problem is that only the template property is different in the two cases. Thus I am trying to figure out how to set the template: property dynamically.

Does any one have a clue how to do this?

Greetz,

Upvotes: 3

Views: 110

Answers (2)

tbwiii
tbwiii

Reputation: 506

Should be as easy as this:

 initialize: function(){
                this.template = options.template;
                return this;
            }

Then when you call it:

var view = new App.Views.WidgetAvailable( { template : '...' } );

Thanks to mu is too short for correction

Upvotes: 3

Jack
Jack

Reputation: 10993

You are able to pass in parameters into your initialize method, so you should be able to just pass in the template.

For example:

App.Views.WidgetAvailable = Backbone.View.extend({

   initialize: function (template) {
           this.template = template(template);

    }
      //the rest of your views code
});

var view1 = new App.Views.WidgetAvailable(template1);
var view2 = new App.Views.WidgetAvailable(template2);

Upvotes: 1

Related Questions