views:

367

answers:

2

If you had to do this...

function addRemoveItemNS() {
  var $newLi = $('<li class="special">special and new <button class="addone">I am new</button> <button class="removeme">remove me</button></li>');
$('#list9 li.special')
  .find('button.addone')
 .unbind('click.addit')
 .bind('click.addit', function() {
   $(this).parent().after($newLi);
   addRemoveItemNS();
  })
  .end()
  .find('button.removeme')
  .unbind('click.removeit')
  .bind('click.removeit', function() {
 $(this).parent().remove();
  });
}
$(document).ready(function() {
  addRemoveItemNS();
});

...with prototype or dojo instead of jquery, how would you do it?

A: 

Well, because there are no events in your code ... or AJAX.

Just a silly request on a misnomer.

rpflo
+3  A: 

Here is how you could do it using the Dojo trunk code (or Dojo 1.4 once it is released). The trunk code adds support for end() to match your original code better. You could get around that by saving the dojo.query(inserted) as a variable and just calling .query() in two separate statements to get the same effect, and then you could use Dojo 1.3.

function addRemoveItemNS() {
  var html = '<li class="special">special and new <button class="addone">I am new</button> <button class="removeme">remove me</button></li>';
  var inserted = dojo.place(html, "list9");
  dojo.query(inserted)
    .query('button.addone')
      .onclick(function(evt){
        addRemoveItemNS()
      })
    .end()
    .query('button.removeme')
      .onclick(function(evt){
        //Use normal DOM API for parentNode to get reference.
        dojo.destroy(evt.target.parentNode);
      });
}

dojo.addOnLoad(function(){
  //First create #list9 node? Missing from original code.
  dojo.place('<ul id="list9"></ul>', dojo.body());
  addRemoveItemNS();
});

Some notes about the code:

  • By using an HTML string, and then dojo.placing it, then there is no need to call for an "unbind".
  • Dojo does not support custom names for binding to events on DOM nodes, just the standard DOM event names, like onclick, onfocus, etc.. are supported.
  • Dojo does not by default make the DOM node that was clicked the "this" reference in the click handlers, since Dojo supports a "this" argument as part of their onclick function. That is why evt.target is used in the remove button click action.
jrburke