0

當我點擊某個東西時,我想對該元素做一些事情(即添加一個類),儘管我不相信事件處理程序中的這個「this」元素實際上是該元素。這裏是我的代碼示例位:如何在Backbone點擊事件中獲得'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(); 

我想將'active'類添加到#something。我會有更多的活動會有不同的課程等,但是現在想要了解一些基礎知識。

此外,接受關於代碼結構的任何建議!

+2

您可能會嘗試檢查displayFirstThing函數的參數。 Backbone可能會傳遞'event'對象,在這種情況下,您可以嘗試使用'event.target'或'event.currentTarget'。 – 2014-11-20 17:26:38

+0

這是一個不錯的提示@GregBurghardt。所以我看到'event.CurrentTarget'是我正在尋找的元素,但是這是傳遞給我的'firstthing'函數嗎? – coffeebytes 2014-11-20 17:34:02

+0

@GregBurghardt或者我想我想知道,有沒有一種方法可以在我的'firstthing'函數中使用'event.currentTarget'? – coffeebytes 2014-11-20 17:45:51

回答

1

骨幹傳遞事件對象作爲第一個參數,從中可以使用currentTarget屬性是接收到事件的元素工作回調。例如。

變種ApplicationView = Backbone.View.extend({

el: $('body'), 

events: { 
    'click #something': 'displayFirstThing' 
}, 

// ... other code 

displayFirstThing: function(event){ 
    $(event.currentTarget).addClass('active'); 
}, 

});

0

我會建議在視圖屬性中存儲要訪問的元素。

var ApplicationView = Backbone.View.extend({ 

    el: $('body'), 

    events: { 
     'click #something': 'displayFirstThing' 
    }, 

    render: function() { 
     // render the view 
     // store the link element in a property 
     this.$something = this.$('#something'); 
    }, 

    displayFirstThing: function(){ 
     this.$something.addClass('someclass'); 
    }, 
}); 
+0

您認爲在視圖或路由器中執行這些類型的操作更合適嗎? – coffeebytes 2014-11-21 14:28:52

+0

ofcourse在看法 – VJAI 2014-11-23 10:22:38

相關問題