0
votes

I'm using Backbonejs routing and trying to get the element that triggered a route, for example if I have:

<a href="#/files" id="link123">Click</a>, is there anyway inside of a route to know which element was clicked so I can get the id or class any arbitrary attribute of that element?

Thanks!

1
Doesn't that kind of defeat the point of routes? They're meant to be bookmarkable, which doesn't work if you make them dependent on a clicked element. Why not just use an ordinary click event? - McGarnagle
why don't you send information along with url like #/files/link123 - Dhiraj
It's a weird case, basically we scroll to certain points of the page based on history, so if your viewing a list of items, we scroll to your previous position on the page. In some cases, we don't want this behavior, so I need a way to know which links were clicked to not enable it. - dzm

1 Answers

0
votes

First off, from the official Backbone documentation:

http://backbonejs.org/#Router-extend

Note that you'll want to avoid using a leading slash in your route definitions

I would recommend following that pattern

Secondly to solve your problem, what you can do is in your view, bind to the 'click' event of your links as such:

events: {
    'click a': 'onClick'
}

where

onClick: function (event) {
    event.preventDefault();
    event.stopPropagation();
    var url = $(event.currentTarget).attr('href');
    // the following line depends on how you implemented your app, this is an example
    window.app.controller.navigate(url, {trigger: true});
}

what this does now, is that you've intercepted in your view, the element that you use to trigger the onClick method.

If you would provide a bit more information as to what exactly you're trying to achieve, perhaps I can elaborate my answer more.