Go to the homepage. Skip navigation and go to the content of this page.

Digital Worlds, thoughts and portfolio of Johan Arensman

April 17 2008

Prototype: Invoking an Insert

Yesterday I was trying to insert serveral links in every fieldset of my form but it just wouldn't work!

I was trying to invoke() the insert() method on every fieldset and creating a new Element each time. The problem was that it did work but after the first element was inserted in the first fieldset, the element was then moved to the next instead of a new element being created.

Not knowing what was causing this I posted a question in the Ruby on Rails: Spinoffs google group and got my answer quite fast:

this one uses only 1 iteration:
$$('form fieldset').each(function(element){ element.insert(new Element('a',{ href: '#' }).update('advanced') .observe('click', function(event) { this.up('form').toggleClassName('simple') }) });

After updating my code to make it work I checked the rest of the comments and saw this:

How about taking advantage of toElement (making insert act like a factory):

$$('form.form fieldset').invoke('insert', {
  toElement: function() {
    return new Element('a').update('advanced')
      .observe('click', function() {
        this.up('form.form').toggleClassName('simple')
      })
  }
})
- kangax

Why haven't I used this before? The usage of the toElement property is clearly under utilized and after reviewing some of my old code I've seen 2 situations where I could use the same solution.

So Kudo's to kangax who posted this heads up!

Digg Submit

Comments

Feel free to add your comment to the discussion.
Your post will be validated first because of the huge amounts of spam posts.

All fields are required and must be valid.
Your E-mail address will be linked to the Gravatar system so create your avatar there now!
The 'Remember my details' checkbox stores your name and e-mail in a cookie on your computer. It is advised not to use this feature on a public computer.

Weblog categories