Topic: RJS page.select enumerable methods

I'm trying to iterate over the DOM elements collected by the RJS page.select method.  This is intended to update the track numbers of a tracklisting to which users can dynamically add and remove tracks.

page.select(".item").each do |element, index|
    page.call 'console.log', index # outputs all indices to the log in Firebug
    page.replace_html element, index # replace the HTML of all items with their updated index
end

This code results in an RJS error that states "TypeError: index.toS is not a function".  Presumably this is because index is a JavaScript object that does not have a to_string function capable of printing it to the page.

If I comment out the page.replace_html element, index line of code, the page.call method happily outputs the index of each element in the collection of DOM elements (div's) of the .item class to the console.

So, I have access to the DOM elements via the element variable, and I have access to the index of each of them via the index variable.  How can I output that index into the div?  I have not been able to find a clear explanation of this either here (http://www.codyfauser.com/2006/03/16/rjs-element-and-collection-proxies) or here (http://dev.rubyonrails.org/changeset/3754), or in the RJS API (.

Thanks for any help!

Re: RJS page.select enumerable methods

I found the answer here: http://ajax.stealthsettings.com/rjs-tem … -methods/.

Because the page.select method returns a JavaScriptElementCollectionProxy object, you can't call that element's properties directly (such as innerHTML) the way you would a DOM element.  Additionally, the compiled JavaScript uses VALUE and INDEX as arguments to the function, regardless of what variables you call in the block (in this case ELEMENT and INDEX).  Thus, this instruction has to be sent to the page as raw JavaScript, and has to address the variables used in the compiled JS rather than those specified in the Ruby block.

So, I updated my code as follows:

    
page.select(".item").each do |element, index|
    # page.replace_html element, index + 1 # expected syntax
    page << "value.innerHTML = index + 1;" # actual syntax
end

This exposes some of the limitations of RJS, but it's still a quick way to update the contents of an element.

Last edited by johnny.rodgers (2007-09-26 12:38:41)