Topic: RJS enumerable methods

I'm trying to iterate over the DOM elements collected by the RJS method.  This is intended to update the track numbers of a tracklisting to which users can dynamically add and remove tracks.".item").each do |element, index| '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

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 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 ( or here (, or in the RJS API (.

Thanks for any help!

Re: RJS enumerable methods

I found the answer here: … -methods/.

Because the 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:".item").each do |element, index|
    # page.replace_html element, index + 1 # expected syntax
    page << "value.innerHTML = index + 1;" # actual syntax

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)