1
votes

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

1
I think you should consider relating your data in a different way. Either the info ('jerk', 'slob') should be part of the route path or it should belong to a model that reacts to the route event.76484

1 Answers

2
votes

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