Reputation: 9358
I'm attempting to implement a Rails 3 application that needs to use the html5 drawing canvas.
So far I have a Sketch scaffold and I've modified the index and show views to be side-by-side (I typed the hidden div in there just to show that I plan to host the canvas in a div):
Currently in the application.js file I have a script that accesses the show action through an Ajax request and places it right next to the Sketches list. Here is the code for that:
// Show individual sketch
$(function(){
var $sketch_div = $('#show_sketch_div');
// return html instead of js
$('a[data-remote]').live('ajax:beforeSend', function(e, xhr, settings){
xhr.setRequestHeader('accept', '*/*;q=0.5, text/html, ' + settings.accepts.html);
});
// Handle sketch name links with the data-remote attribute
$('a[data-remote]').live('ajax:success', function(xhr, data, status){
$sketch_div
.html(data)
.show();
});
});
Also, each of the links in the Sketches list has a class associated with it (in order to grab it with JQuery):
<td><%= link_to 'Show', sketch, :remote => true, :class => 'show_sketch_button' %></td>
I have the Sketch controller set up to render JSON:
def show @sketch = Sketch.find(params[:id])
respond_to do |format| format.html # show.html.erb format.xml { render :xml => @sketch } format.json { render :json => @sketch } end
end
This part is where I'm really stuck.
I plan on using JQuery to insert a Canvas tag whenever a Sketch's show button is clicked. However, I have no idea how to get the id paramater of the associated sketch with Javascript and then use that to generate a Canvas element that is only associated with that particular id.
I've searched for JSON tutorials but I can't find anything that seems to address what I'm trying to do. I'm also very new to JSON - so I could just be missing it.
Does anyone have any ideas or an example that you can point me to?
Upvotes: 3
Views: 1677
Reputation: 3740
If i'm right, you wanna write the ID of a sketch object into your html, to use that later on with JavaScript.
Create a "data-" html5 attribute into your link_to tag. In html5 you can create tags beginning with "data-" witch are going to be valid.
<%= link_to 'Show', sketch, :remote => true, :class => 'show_sketch_button', :"data-sketch-id" => sketch.id %>
In jQuery, you can get this element with $('a.show_sketch_button[data-sketch-id="<NUMBER>"]')
Btw, i wouldn't recommend using .live event handling. Its parsing the full DOM every time there's a change in it. Instead of, just use .bind(), .unbind() <--- if u need to remove the eventhandler.
Upvotes: 3