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.
-
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.three– three2013-02-18 10:13:04 +00:00Commented Feb 18, 2013 at 10:13
1 Answer
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
2 Comments
$(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.