Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Binding objects parsed from JSON to classes

I want to pull a tree structured set of objects from a web service represented with JSON

When I unpack that, I'll wind up with a structure which uses vanilla Javascript objects. What I'd like to be able to do is bind each node to a specific class, so that method calls become available on each node of the tree.

My solution, using jQuery .extend()

Here's a simplified example which illustrates the approach.

I might define a simple class using jQuery .extend() as follows...

MyNode= function() {
  this.init();
}

$.extend(MyNode.prototype, {
   init: function() {
     // do initialization here
   },

   getName: function() {
     return this.nodeName;
   }
});

Now given a simple object like this

var tree={
    nodeName:'frumious',
    nodeType:'MyNode'
}

I can make the object appear to be an instance of the desired nodeType with

$.extend(tree, eval(tree.nodeType+'.prototype'));

Note that I want the object to declare the class name, so I've used eval to locate the appropriate prototype for that class. (Thanks to Rob W for suggesting window[tree.nodeType].prototype as a better alternative)

Now I can do things like alert(tree.getName());

Better ways?

I write StackOverflow questions and find the act of describing it in enough detail to avoid a downvote is enough for me to solve it myself. This was no exception, but I'd be interested to hear of any more elegant approaches to this problem. This solution gets the job done, but I can't help but feel there must be other approaches...

like image 944
Paul Dixon Avatar asked Nov 04 '22 07:11

Paul Dixon


1 Answers

I'd get rid off eval, and use:

$.extend(tree, window[tree.nodeType].prototype);

If MyNode is a local, but known variable, add it to an object, for reference. Eg:

var collection = {};
collection['MyNode'] = MyNode;
$.extend(tree, collection[tree.nodeType].prototype);

Alternatively, if the structure of the JSON is solid, I recommend a custom JSON parser, which also allows you to validate properties prior addition.

like image 86
Rob W Avatar answered Nov 07 '22 20:11

Rob W