我有一个小骨干班:
view = Backbone.View.extend({
events: {
"click textarea" : "doSomething"
},
doSomething : function() {
var textarea = $(this.el).find('textarea')
// I would like to just call, this.textarea, or this.elements.textarea
}
});
理想情况下,我希望能够通过变量访问我的textarea,而不必每次都搜索元素。任何人都知道如何做到这一点?
答案 0 :(得分:1)
也许我正在思考它,但是如何在需要的时候特别给予textarea一个类或id和目标,
或创建一个生成textarea的子视图
var View = Backbone.View.extend({
el: '#main',
initialize: function(){
this.render();
},
render: function() {
var subview = new SubView();
this.$('form').append(subview.el);
this.$('form').show();
},
});
var SubView = Backbone.View.extend({
tagName: 'textarea',
id: 'whateverId',
events: {
"click" : "doSomething"
},
initialize: function(){
this.render();
},
doSomething : function(event) {
var textarea = $(event.target);
// or var textarea = $(this.el);
},
render: function(){
return $(this.el);
}
});
答案 1 :(得分:1)
其他答案为您提供所需的参考,但如果您真的需要textarea的句柄,那么您可以这样做:
view = Backbone.View.extend({
initialize: function() {
this.myTextareaElement = $(this.el).find('textarea')
}
events: {
"click textarea" : "doSomething"
},
doSomething : function() {
// use this.myTextareaElement ...
}
});
答案 2 :(得分:0)
将事件作为参数传递,然后使用事件目标
view = Backbone.View.extend({
events: {
"click textarea" : "doSomething"
},
doSomething : function(event) {
var textarea = $(event.target);
}
});