【发布时间】:2015-01-18 16:06:17
【问题描述】:
当我点击某个东西时,我想对该元素做一些事情(即添加一个类),尽管我不相信我的事件处理程序中的这个“this”元素实际上就是那个元素。这是我的代码的一个示例:
var ApplicationRouter = Backbone.Router.extend({
routes: {
"": "home",
"firstthing": "firstthing",
},
firstthing: function() {
$(this).addClass('active');
}
});
var ApplicationView = Backbone.View.extend({
el: $('body'),
events: {
'click #something': 'displayFirstThing'
},
initialize: function(){
this.router = new ApplicationRouter();
Backbone.history.start();
},
displayFirstThing: function(){
this.router.navigate("firstthing", true);
},
});
new ApplicationView();
我想将“活动”类添加到#something。我将举办更多活动,这些活动将有不同的课程等,但现在希望了解一些基础知识。
另外,接受任何关于代码结构的建议!
【问题讨论】:
-
您可以尝试检查
arguments 到 displayFirstThing 函数。 Backbone 可能正在传递event对象,在这种情况下,您可以尝试使用event.target或event.currentTarget。 -
这是一个很好的提示@GregBurghardt。所以我看到
event.CurrentTarget是我正在寻找的元素,但这是否被传递到我的firstthing函数中? -
@GregBurghardt 或者我想我想知道,有没有办法在我的
firstthing函数中使用event.currentTarget? -
event.currentTarget属性应该是委托事件的目标。在你的情况下,我认为event.currentTarget.id应该是"something"。您的代码可能是:event.currentTarget.classList.add("active")。您的 displayFirstThing 方法是否将事件对象作为参数?我只是好奇。除了试验之外,我没有使用过 Backbone。 -
你说得对,我的
event.currentTarget.id是something。我在displayFirstThing函数中使用了console.log(event.currentTarget.id),得到了something的值。在我的 displayFirstThing 方法中使用event.currentTarget.classList.add("active")确实有效,但现在我想知道我的firstthing方法的目的是什么?比如为什么不在我的displayFirstThing方法中包含所有这些代码?
标签: jquery backbone.js backbone-views backbone-events backbone-routing