jQuery data() JSON Encoding issues -
in current jquery mobile application trap click events on variety of html elements, extract whole set of data-* attributes element using
var data = $(element).data();
package json string
var json = json.stringify(data);
and send off elsewhere downstream processing.
the problem have run (and pretty sure has started recent versions of jquery mobile) elements such radios, checkboxes , buttons have annonymous functions part of data() array. serializing such functions is
- not relevent application
- more importantly, triggers javascript along lines of "an attempt made use object no longer valid"...
by dint of experiment have found issue anonymous functions turn in raw data() object as
- buttonelements
- mobile-checkboxradio
etc. build own object serialize devoid of these offending entities.
this ok have found issue. change jqm version , boom, problem crops on again since attribute name has changed (e.g. mobilecheckboxradio in place of mobile-checkboxradio).
question - suggest more generic, attribute name agnostic, way of stripping out these offensive bits? own efforts , trying figure out typeof of object attribute have failed since string. suppose check phrase "annonymous function" in string sounds clumsy.
i figured out way this. 1 can following
var data = $(element).data(); $.each(data,function(key,prop){if ('object' != typeof(prop)) /*do */)}
here fiddle demonstrating happens radio button. note 2 of data-* attributes returned objects. 1 of them, mobilecheckboxradio anonymous function. try serialize data , exception - being trapped , reported. safely cloned object, shorn of anon function goes well.
this has benefit of being "version proof". whether better checking small handful of attributes liable cause such errors debatable.
Comments
Post a Comment