0

I've got a Backbone View which when I instantiate it, want to give it an attribute. I currently try to do this like so:

var myView = new MyView({'someId': 123});

and in MyView I do:

var Myview = Backbone.View.extend({
    events: {'click .some-class': 'myMethod'},
    myMethod: function(e){
        console.log(this.someId);
    },
    // and some other things here..
});

When I click the some-class button I get a console message saying "undefined". I also tried it with the following:

myView.set({'someId': 123});

but that also doesn't work.

Any idea what I'm doing wrong? All tips are welcome!

kramer65
  • 50,427
  • 120
  • 308
  • 488

1 Answers1

1

Pass it via the initialize options:

var Myview = Backbone.View.extend({
    initialize: function(options){
        this.someId = options.someId; 
    }, 
    events: {'click .some-class': 'myMethod'},
    myMethod: function(e){
        console.log(this.someId);
    },
    // and some other things here..
});
html_programmer
  • 18,126
  • 18
  • 85
  • 158