简体   繁体   中英

Custom routes don't work with setTimeout

For example, my routes.rb looks like:

...
get 'abc/xyz' => 'abc#xyz', :as => 'abc_xyz'
...

application.js:

...
$('a').click(showSpinner);
function showSpinner(evt) {
    link = $(this);
    evt.preventDefault();
    $('body').append('<div class="spinner-overlay"></div>');
    setTimeout(function() {
        window.location = link.attr('href');
    }, 10);
});
...

When a link using that JavaScript goes to abc_xyz_path, it gives an ActiveRecord RecordNotFound error since it's looking for the abc record with id xyz instead of using the custom route. If I remove the setTimeout, however, there's no problem and it works. Does Rails' routing system have a problem with timeouts?

UPDATE:

I realized I didn't need the preventDefault() or setTimeout(), since this click handler would happen before the link redirected anyway. Problem solved.

The fact that your link works without javascript indicates that it's pointing to the correct URL. Rails won't know or care wether the request came after a javascript timeout or not, so that's not the issue.

So, the problem is that your line:

window.location = link.attr('href');

must be setting the wrong url. You should do:

console.log(link.attr('href'));

to check what it's getting, and update your question with that. I don't know what link is, but according to your code sample, it's not mentioned other than in the line window.location = link.attr('href');

What I'd be doing instead is:

window.location = $(this).attr('href');

$(this) will refer to the think that just received the click event, which is what you want.

I realized I didn't need the preventDefault() or setTimeout(), since this click handler would happen before the link redirected anyway. No more problems.

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