How can I pass a parameter into a Backbone.js view

2019-04-14 08:16发布

问题:

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.

回答1:

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!



回答2:

stuff that is not unique to the framwork goes to options

look in

this.options.magic



回答3:

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.