Advertisement
mrrena

MooTools add-ons: Elem.fromJSON, Elem.toJSON, Elem.toObject

May 13th, 2012
166
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /* http://mrrena.blogspot.com/2011/03/dom-input-element-understanding.html
  2. Requires MooTools 1.4.5 or higher: http://mootools.net
  3.  
  4. Provides:
  5.   Element.fromJSON(jsonString);
  6.   Element.toJSON();
  7.   Element.toObject();
  8.  
  9. Example:
  10.    (Note that "name" attribute MUST be specified on input elements):
  11.  
  12.     <div id="wrapper">
  13.       <input type="text" name="name" />
  14.       <input type="text" name="pass" />
  15.       <input type="checkbox" name="trueFalse" />
  16.     </div>
  17.  
  18.     // pre-fill all corresponding form elements inside wrapper with passed JSON string
  19.     $('wrapper').fromJSON({
  20.         "name": "Frank",
  21.         "pass": "5csaU}8&",
  22.         "trueFalse": true
  23.     });
  24.  
  25.     $('wrapper').toJSON(); // outputs {"name":"Frank","pass":"5csaU}8&","trueFalse":true}
  26.     $('wrapper').toObject(); // same, except as an object rather than a JSON string
  27. */
  28.  
  29. var ElementFunctions = {
  30.    
  31.     /**
  32.      * Method: Element.fromJSON
  33.      *  Gathers all the child elements of the element, and checks to see if
  34.      *  their name matches any of the keys in the passed "jsonObj." If there is
  35.      *  a match, the input's "value" is assigned the value of the matching key.
  36.      *  This method can be used to populate inputs from the server easily in
  37.      *  one simple call.
  38.      *
  39.      * Parameter:
  40.      *  jsonObj (obj || array) - the JSON response object from the server
  41.      *
  42.      * Returns: nothing
  43.      */
  44.     fromJSON: function(jsonObj) {
  45.  
  46.         var self = this;
  47.  
  48.         //Process Name/Value
  49.         self.fromJSON.nameValue = function(obj) {
  50.             for (var x in obj) {
  51.                 var elements = self.getElements('[name=' + x + ']');
  52.                 if (elements.length == 1) {
  53.                     elements[0].set('value', (obj[x]) ? obj[x] : '');
  54.                     // MSIE 7 and 8 compatibility for select boxes. If options do not have a 'value' attribute, this compability layer is required.
  55.                     // That is, if less than version 9 of IE, if a select box, if the value is not already set, and if a value is specified, then...
  56.                     if (Browser.ie && Browser.version < 9 && elements[0].tagName == 'SELECT' && !$isNotNull(elements[0].get('value')) && $isNotNull(obj[x])) {
  57.                         elements[0].selectedIndex = elements[0].getElements('option').get('html').indexOf(obj[x]);//important! we get the html, not the value
  58.                     }
  59.                     if (typeof(elements[0].getAttribute('checked')) !== undefined) {
  60.                         elements[0].checked = (obj[x]) ? true : false;//click checkboxes
  61.                     }
  62.                 }
  63.                 else if (elements.length > 1) {
  64.                     elements.each(function(item, index, array) {
  65.                         if (item.get('value') == obj[x]) {
  66.                             item.checked = true;
  67.                         }
  68.                     });
  69.                 }
  70.             }
  71.         };
  72.  
  73.         if (typeOf(jsonObj) == 'object') {
  74.             self.fromJSON.nameValue(jsonObj);
  75.         }
  76.     },
  77.  
  78.     /**
  79.      * Method: Element.toJSON
  80.      *  Wraps the results of calling <toObj> in a JSON-encoded string
  81.      *
  82.      * Returns:
  83.      *  JSON (string) - A JSON "object" containing element values
  84.      */
  85.     toJSON: function() {
  86.         return JSON.encode(this.toObject());
  87.     },
  88.  
  89.     /**
  90.      * Method: Element.toObject
  91.      *  Gathers values for the input element if it has a "name" attribute along
  92.      *  with any child input elements with a name, placing them in an object.
  93.      *  This object has the following format, with a key/value pair for each
  94.      *  named input element
  95.      *
  96.      *   {
  97.      *       elementName: elementValue
  98.      *   }
  99.      *
  100.      *  Returns:
  101.      *   JSON (string) - An object containing element values
  102.      */
  103.     toObject: function() {
  104.  
  105.         var collectionObj = {};
  106.         var elArray = this.getElements('input, select, textarea', true);
  107.  
  108.         if (/(input|select|textarea)/.test(this.get('tag'))) {
  109.             elArray.include(this);
  110.         }
  111.         elArray.each(function(el) {
  112.  
  113.             var name = el.name;
  114.             if (!name) {
  115.                 return '';
  116.             }
  117.             var value = $(el).get('value');
  118.             if (el.type == 'checkbox') {
  119.                 value = (value !== false && value !== 'off') ? true : false;
  120.             }
  121.  
  122.             Array.from(value).each(function(val) {
  123.                 collectionObj[name] = val;
  124.             });
  125.         });
  126.  
  127.         return collectionObj;
  128.     }
  129. };
  130. Element.implement(ElementFunctions);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement