Search code examples
javascriptbackbone.js

how to pass the event (to access data-attribute) when clicking link in Backbone router


I have routes like this in a Backbone app

<a href="/2015/09/28/do-you-drink-whiskey" data-info="jerk">link</a>
<a href="/2015/09/29/do-you-drink-beer/" data-info="slob">link</a>

If I click on the links, only the path (and not the data-attribute) is passed to the Backbone router try it on this js fiddle.

Question: is there a way to make the data-attribute available when the link is clicked in this situation?

var R = Backbone.Router.extend({
    routes:{
        "": "list",
        "restaurants/:id": "restoDetails",
        "2015/*splat": "matchAnything"
    },
    matchAnything: function(e){
        console.log("yeah, match", e)
    },
    restoDetails: function() {
        console.log('restoDetails', arguments);
    },
    list: function() {
        console.log('list', arguments);
    }
});

$(document).on('click', 'a[href^="/"]', function(e){
    e.preventDefault();
    var href = $(e.currentTarget).attr('href');
    Backbone.history.navigate(href, {trigger: true});
});
new R();
Backbone.history.start({pushState: true});

Update

You can see here in this fiddle that even with jQuery (as the first answer posted proposed)the data attribute is inaccessible because Backbone is not passing the event


Solution

  • Use jQuery data() function jQuery data

    var info = $(e.currentTarget).data('info');
    

    also you can use

    $(this)
    

    instead of

    $(e.currentTarget)
    

    Update

    to get data-info inside function matchAnything following works

    var R = Backbone.Router.extend({
        routes:{
            "": "list",
            "restaurants/:id": "restoDetails",
            "2015/*splat": "matchAnything"
        },
        matchAnything: function(e){
            var info = lastElementClicked.data('info');
            console.log(info, "info?");
        },
        restoDetails: function() {
            console.log('restoDetails', arguments);
        },
        list: function() {
            console.log('list', arguments);
        }
    });
    
    var lastElementClicked;
    
    $(document).on('click', 'a[href^="/"]', function(e){
        e.preventDefault();
        lastElementClicked = $(this)
        var href = lastElementClicked.attr('href');
        Backbone.history.navigate(href, {trigger: true});
    });
    new R();
    Backbone.history.start({pushState: true});