[英]How can I pass a parameter into a Backbone.js view?
I'm trying to pass a parameter into a Backbone.js view, but I'm having trouble doing it. 我正在尝试将参数传递给Backbone.js视图,但我无法做到这一点。
I have a Backbone view as follows: 我有一个Backbone视图如下:
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... 我不明白为什么
el
工作得很好(我可以使用jquery使用它来访问它this.$el.
),但是this.magic
和this.templateString
都是未定义的...
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.
我最初尝试传递一个渲染函数(并从骨干视图类中删除它),但是当它不起作用时我尝试传递简单的数据类型而不是......我假设无论需要做什么来传递一个我的第一个问题的参数将用于传递函数。
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.
T'非常简单......只需快速检查一下Backbone.js文档......应该先完成。
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 传入时的以下参数会自动分配给视图(可以使用
this.variableName
访问它们的AKA):model,collection,el,id,className,tagName和attributes
ALL OTHER VARIABLES can be accessed with this.options.variableName
. 可以使用
this.options.variableName
访问所有其他变量。
From my example above, I can get access to magic
by using this.options.magic
, instead of this.magic
. 从我上面的例子中,我可以通过使用
this.options.magic
而不是this.magic
来获取magic
。
Yay! 好极了!
stuff that is not unique to the framwork goes to options 那些不是framwork独有的东西可以选择
look in 顺便拜访
this.options.magic
In more recent version of Backbone (mine is 1.1.2) you can copy View constructor options this way: 在最新版本的Backbone(我的是1.1.2)中,您可以通过以下方式复制View构造函数选项:
initialize: function(options) {
_.extend(this, _.pick(options, 'several', 'specific', 'options'));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.