2

I'm trying to pass a parameter into a Backbone.js view, but I'm having trouble doing it.

I have a Backbone view as follows:

var DataTypesView = Backbone.View.extend({
    events:{
        'click .datatype': 'add'
    },
    initialize: function(){
        console.log(this.magic);
        this.render();
    },
    render: function(){
        console.log('printing template');
        console.log(this.templateString);

                    etc.
}});

Later, I crate the view as follows:

        dataTypesView = new DataTypesView({magic:true,el:$('#dataViewSpace'),templateString:'#template'});

It doesn't work. What I don't understand is why the el works just fine (and I can access it using jquery with this.$el.), yet this.magic and this.templateString are both undefined...

Is there any way that I can pass a parameter into a view in the way I'm trying to above?

On a related note - is there any way I can pass the render function in? I initially tried passing a render function in (and removing it from the backbone view class), but when that didn't work I tried passing in simple datatypes instead... I'm assuming that whatever needs to be done to pass in a parameter for my first question will work for passing in a function.

3 Answers 3

6

EDIT - apparently this answer doesn't work in newer versions of Backbone.

I figured it out! T'was pretty straightforward... All it took was a quick check of the Backbone.js documentation... should have done that first.

The following parameters when passed in are automatically assigned to the view (AKA you can access them with this.variableName): model, collection, el, id, className, tagName and attributes

ALL OTHER VARIABLES can be accessed with this.options.variableName.

From my example above, I can get access to magic by using this.options.magic, instead of this.magic.

Yay!

1
  • This doesnt work for me. There is no options object in the view at all.
    – iankit
    Oct 29, 2015 at 11:18
2

stuff that is not unique to the framwork goes to options

look in

this.options.magic

1
  • 3
    hey lior - if you make your answer a little more informative (AKA include the extra info that I've included in my answer), then I'll accept your answer. Otherwise, I'll accept my own once I am able to.
    – thisissami
    Jul 10, 2013 at 4:00
2

In more recent version of Backbone (mine is 1.1.2) you can copy View constructor options this way:

initialize: function(options) {
  _.extend(this, _.pick(options, 'several', 'specific', 'options'));
}

Credits goes to this github issue.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.