[英]Using current jQuery element in backbone.js view
Am slowing get a hang of backbone.js, but i've run into a bit of bind. 越来越不了解骨干.js,但我遇到了一些束缚。 I've successfully created a view, and am able to delegate events to element in the DOM, however i can seem to be able to use the jQuery " $(this)
" in the following context 我已经成功创建了一个视图,并且能够将事件委托给DOM中的元素,但是在以下情况下,我似乎可以使用jQuery“ $(this)
”
Chrono.Views.Sidebar = Backbone.View.extend({
//Page wrapper
el:"#wrapper",
//Delegate events to elements
events : {
"click .push-to":"loadPage"
},
loadPage: function(event) {
var url = $(this).attr("href");
alert(url);
event.preventDefault();
}
});
The click event is intercept but this line "var url = $(this).attr("href");" 点击事件是拦截事件,但这一行“ var url = $(this).attr(“ href”);“
In the context of loadPage
, this
has been bound to your Chrono.Views.Sidebar
instance. 在loadPage
的上下文中, this
已绑定到您的Chrono.Views.Sidebar
实例。 However, you can get the DOM element that the event was triggered on through event.currentTarget
. 但是,您可以通过event.currentTarget
获取触发事件的DOM元素。 If you update your function to look like this it should work: 如果您将函数更新为如下所示,则它应该可以工作:
loadPage: function(event) {
var url = $(event.currentTarget).attr("href");
alert(url);
event.preventDefault();
}
In backbone this is bound to the view, but you can still get the element that was clicked by checking the event.target or the element that the event was bound to using event.currentTarget. 在主干中,它绑定到视图,但是您仍然可以通过使用event.currentTarget检查event.target或绑定到事件的元素来获取被单击的元素。
Take a look at this question Backbone.js Event Binding 看看这个问题Backbone.js事件绑定
this
is bound to the view, so you can access the View.$el
property directly. this
是绑定到视图的,因此您可以直接访问View.$el
属性。
loadPage: function(event) {
var url = this.$el.find('.push-to').attr('href');
alert(url);
event.preventDefault();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.