views:

49

answers:

2

I am looking for a way to create an in-place editor in JavaScript like JEditable or similar plugins. However, the difference is that my editor would be a multi-field form rather than single field.

Since the same form will be used in different parts, i.e. editing existing items and creating new items, I would like to be able to specify the callback function for each case while not having to duplicate the shared functionality (e.g. validation, cancel button, etc.).

Currently I tried implementing it naively and the code looks awful as event handlers are scattering around the source code instead of being together as a component.

So my question is what is the recommended way to implement this? If there is a jQuery plugin that provide the functionality, that might be the easiest route. Otherwise, how would I structure my code properly?

A: 

The problem is that you need to separate the data from the displayed text. For each chunk of data you display, associate a json dict (written into the page, or pulled with ajax) with the text for each field in the form.

For example, if you're working with names (first, middle, last), you display the name like this:

<span class="editable">Colin M. Hansen</span>

and you write the form like this:

<form class="nameform" style="display: none;">
     <input class="first" type="text">
     <input class="mi" type="text">
     <input class="last" type="text">
</form>

and you have a dict like this, mapped to the inputs in the form:

name1 = {
    first: 'Colin',
    mi: 'M',
    last: 'Hansen'
};

The common code you write switches the form in for the text on the onclick of the span element, and fills each input field with data from the dict. The submit code saves the new data to name1 and to the server, and returns the new display text.

colinmarc
A: 

Seperate the definition of your callbacks and do a lookup in the editable callback to your desired callback

var callbacks = {  // define your callbacks here
  'field1': function() {
    alert("You editted field1");
  },
  'field2': function() {
    alert("You editted field2");
  }
}

$("input").each(function(i, o) {
  $(o).editable('save.php', {
    'callback': function(value, settings) {
       // do validation etc.

       // then call field-specific callback
      if(callbacks[o.name]) {  // I'm using 'name', but you could also use 'id' or something else
         callbacks[o.name]();
      }
    }
  });
});
Gate
In my case, I want a callback only for form submit button, not for every field. The whole form should be show/hide/submit/cancel as a whole.
ejel