简体   繁体   中英

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. 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

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");"

In the context of loadPage , this has been bound to your Chrono.Views.Sidebar instance. However, you can get the DOM element that the event was triggered on through event.currentTarget . 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.

Take a look at this question Backbone.js Event Binding

this is bound to the view, so you can access the View.$el property directly.

loadPage: function(event) {
    var url = this.$el.find('.push-to').attr('href');
    alert(url);
    event.preventDefault();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM