[thelist] JSON and Client-side classes

sam foster potatosculptor at gmail.com
Thu Sep 14 10:05:17 CDT 2006


That's one of the drawbacks of JSON (partly inherent in javascript) is
that there's no good way to indicate type: you have strings/integers,
objects and arrays. Anything else you have to "cast" yourself.  I
think there are some conventions emerging - for things like dates and
so on, and some of the more common data types people are wanting to
pass around.

> var newGuy = eval('(' + jsonString + ')');
>
> So with a little foresight (both server and client know about the
> object to create, security safeguards, etc.) a php script could send
> down a brand spanking new object to the client without the extra
> steps of creating a new object and then decorating it with the
> returned data.

You are always going to have to do some parsing (even if it just takes
the form of eval) on the client side. One way to do that is handle it
in the constructor:

function Person(props) {
  this._mixin(obj) {
    for(var key in obj) {
      this[key] = obj[key];
    }
  }
  if(arguments[0] instanceof String) {
    props = eval(props);
  }
  if(props instanceof Object) {
    this._mixin(props);
  }
}

Or use a factory object that makes class instances given a string?

function PersonFactory() {}
PersonFactory.createPerson(props) {
  return new Person(props);
}

PersonFactory.createPersonFromJsonString(strProps) {
  var props = eval(strProps); // or JSON.parse(strProps);
  return new Person(props);
}

I see the first technique used a lot in dojo - where functions are
very liberal in what they accept and there's a lot of logic in there
to coerce everything into the right shape. On the other hand, the
Factory approach is arguably cleaner and leaner in a lot of cases.

Another convention I see in Dojo (like everything probably borrowed
from best practices elsewhere) is to have an alternate function that
explicitly accept an object with key/values, vs. the normal list of
arguments, e.g. dojo.event.connect(arg1,arg2,arg2 ..), and
dojo.event.kwConnect(obj)

Sam



More information about the thelist mailing list