Reputation: 141
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.
Upvotes: 1
Views: 1183
Reputation: 9622
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
Upvotes: 5