1

In rails, it is possible to set :remote => true to make a remote call to the web application. One can then respond with a .js.erb to changes elements. How would I create this in Sinatra? I want to do a remote delete on a resource and if successful, update Dom, else throw error.

1
  • you can add a delete route for the resource and answer with a status code. You can call this route with an ajax call from the client. Commented Feb 18, 2013 at 10:13

1 Answer 1

5

In Rails, setting :remote => true using the link_to helper results in the following output:

<a href="#yoururl" data-remote="true">Linktext</a>

This link is observed in rails.js via something like:

$(document).on('click.remote', '[data-remote]', function() {
  $.ajax({
    url: $(this).attr('href'),
    type: $(this).data('method') || 'GET',
    // and so on...
  });
});

What it therefore actually does is mark your HTML link with the data-remote="true" attribute, and then handles it via js. The js.erb template you can respond with is then evaled via the DOM. (Which I personally think is a bad idea).

In Sinatra, you can do pretty much the same: Mark your links with, for example, a remote class (which provides a faster lookup for js than the one rails uses via [data-remote]:

<a href="#yoururl" class="remote">Your Link Text</a>

Then bind the links having the remote class via jQuery: Observe the whole document for click events originating from elements with the remote class the way rails does it:

$(document).on('click.remote', '.remote', function() {
  // a similar ajax call to the one rails uses
});

Then, respond with JSON in sinatra and Sinatra::JSON:

get '/yoururl' do
  json :foo => 'bar'
end

And do what you like with the data in the success handler of the ajax call. Or, you can also respond with a script written in erb (which is what rails does with .js.erb):

get '/yoururl' do
  erb :"answer.js"
end
Sign up to request clarification or add additional context in comments.

2 Comments

Haven't tried it yet but looks about right. Thanks for digging into rails.js and finding the answer..I didn't know where to look. Would you be able to tell me what this particular line does? on('click.remote', '.remote' => click.remote? I know .remote targets the class remote
$(document).on('click.remote', '.remote', function() {}) installs an observer looking for click events originating from elements having the class remote bubbling to the document. The remote in the event type string (click.remote) is a namespace helping you to be able to unbind just that handler using off('click.remote'). Without the namespace, you would only be able to unbind all the click events bound to document, which is not very flexible.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.