I have some code that makes a Backbone.View, based on some params I pass to it, like so:
// The Form View
var FormView = Backbone.View.extend({
initialize: function (opts) {
debugger; // This is here only to figure out what gets executed first: if "id" method or "initialize"
this.options = {};
this.options.id = opts.id;
this.options.className = opts.class;
},
id: function () {
debugger; // The application will stop here before the debugger I set in the initialize method
return this.options.id; // options is undefined!
},
className: function () {
return this.options.className; // options is undefined!
}
});
// The params
var params =
fid: "some-form",
class: "form-horizontal"
};
var myForm = new FormView(params);
But the this.options
property is always undefined
. As I can see, the method that sets the view's properties runs BEFORE the initialize
method. As a workaround I think I could access the initialize method inside de id callback and call its arguments, but I'm not sure how to do this properly. And I don't think this is a good approach either.
Any ideas? - Thanks in advance.
Why don't you use the usual way of passing options to the view? Something like:
var FormView = Backbone.View.extend({
initialize: function () {
this.foo = this.options.foo;
this.bar = this.options.bar;
}
});
var params = {foo: '1', bar: '2'};
var v = new FormView(params);
You can also pass as params {id: '1', className: 'your-class'}
and Backbone will apply it automatically to the respective id
and className
properties of the target View
.
You don't seem to be initializing the options
attribute properly. You should have
initialize: function (opts) {
this.options = {}; // you were missing this part
this.options.id = opts.id;
this.options.className = opts.class;
},
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.