RJS question

I have the following code on an RJS template.

counter = 0
page.select(’#mediators li’).each do |t|
counter += 1
end

that’s translated into Javascript as:

try {
$$("#mediators li").each(function(value, index) {
});

The problem is the counter variable always comes back as “1” no matter
how many

  • elements there are.

    I’d like to be able to count the

  • tags so I can use it as a local
    variable on a page.insert_html like this:

    page.insert_html :bottom, ‘mediators’, :partial => ‘mediator’, :locals
    => { :mediator => counter }

    How would I do that?

  • counter is a ruby, server-side variable, evaluated before javascript
    code is executed.
    You can use a javascript, client-side variable, like in this code (not
    tested)

    page << “counter = 0”
    page.select(’#mediators li’).each do |t|
    page << “counter += 1”
    end

    Now you must change your mediator partial, in order to use the counter
    javascript variable.

    Regards
    Massimo
    http://www.addsw.it

    Sr.G.O. wrote:

    I have the following code on an RJS template.

    counter = 0
    page.select(’#mediators li’).each do |t|
    counter += 1
    end
    (…)
    The problem is the counter variable always comes back as “1” no matter
    how many

  • elements there are.
    (…)
  • Hi, try using a global variable instead.

    Good luck,

    -Conrad

    Yeah that works a bit better:

    counter = 0

    $$("#mediators li").each(function(value, index) {

    counter += 1

    });

    It makes “counter” a javascript variable but the problem is how to pass
    it as a local variable on the RJS:

    page.insert_html :bottom, ‘mediators’, :partial => ‘mediator’, :locals
    => { :mediator => counter }

    Massimo wrote:

    counter is a ruby, server-side variable, evaluated before javascript
    code is executed.
    You can use a javascript, client-side variable, like in this code (not
    tested)

    page << “counter = 0”
    page.select(’#mediators li’).each do |t|
    page << “counter += 1”
    end

    Now you must change your mediator partial, in order to use the counter
    javascript variable.

    Regards
    Massimo
    http://www.addsw.it

    Sr.G.O. wrote:

    I have the following code on an RJS template.

    counter = 0
    page.select(’#mediators li’).each do |t|
    counter += 1
    end
    (…)
    The problem is the counter variable always comes back as “1” no matter
    how many

  • elements there are.
    (…)
  • This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

    | Privacy Policy | Terms of Service | Remote Ruby Jobs