[英]Using variable for selectors in events
for some reason I need to use a variable as the selector for events in backbone, but I can't figure how to do this : 由于某种原因,我需要使用一个变量作为骨干事件的选择器,但我无法想象如何做到这一点:
app.views.Selfcare = Backbone.View.extend({
events: {
click window.parent.document .close : "closeWindow"
},
closeWindow: function() {
//code
}
});
I have to use a different scope and I can't do "click .close" : "closeWindow". 我必须使用不同的范围,我不能做“click .close”:“closeWindow”。
Thx for your help. 谢谢你的帮助。
I had a look at Backbone.js's source code and found out that if your view's events
is a function then the function is called and it's return value is used as the events
object. 我查看了Backbone.js的源代码,发现如果你的视图的events
是一个函数,那么函数被调用,它的返回值被用作events
对象。
This means that your code can be changed like this: 这意味着您的代码可以像这样更改:
app.views.Selfcare = Backbone.View.extend({
events: function() {
var _events = {
// all "standard" events can be here if you like
}
_events["events" + "with variables"] = "closeWindow";
return _events;
},
closeWindow: function() {
//code
}
});
THIS is the interesting part of the source code: 这是源代码中有趣的部分:
if (_.isFunction(events)) events = events.call(this);
Update: 更新:
Example is available on JSFiddle HERE ** JSFiddle HERE上提供了示例**
I'm not sure that you'll be able to use a variable there. 我不确定你能否在那里使用变量。 You could use the built-in Events methods (see documentation ) to add a custom listener, then add an event listener to window.parent.document
to trigger that custom event (use the Events.trigger method). 您可以使用内置的Events方法(请参阅文档 )添加自定义侦听器,然后向window.parent.document
添加一个事件侦听器以触发该自定义事件(使用Events.trigger方法)。
That said, it would be much easier to decouple this event from Backbone entirely (unless you don't want to do that), and go down the addEventListener route: 也就是说,将此事件与Backbone完全分离会更容易(除非您不想这样做),然后沿着addEventListener路由:
app.views.Selfcare = Backbone.View.extend({
initialize: function() {
_.bindAll(this, 'render', 'closeWindow');
if(this.options.clickTarget) {
this.options.clickTarget.addEventListener('click', this.closeWindow, false);
}
},
render: function() {
// Render to the DOM here
return this; // as per Backbone conventions
},
closeWindow: function() {
// Stuff here
}
});
// Usage:
var mySelfcare = new app.views.Selfcare({
clickTarget: window.parent.document
});
I think that should work, although I haven't tested it (and there may be one or two syntactical errors!) 我认为这应该有用,虽然我没有测试过(并且可能有一两个语法错误!)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.