Note that there are some explanatory texts on larger screens.

plurals
  1. POBinding objects parsed from JSON to classes
    primarykey
    data
    text
    <p>I want to pull a tree structured set of objects from a web service represented with JSON</p> <p>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.</p> <h2>My solution, using jQuery .extend()</h2> <p>Here's a simplified example which illustrates the approach.</p> <p>I might define a simple class using jQuery <a href="http://api.jquery.com/jQuery.extend/" rel="nofollow noreferrer">.extend()</a> as follows...</p> <pre><code>MyNode= function() { this.init(); } $.extend(MyNode.prototype, { init: function() { // do initialization here }, getName: function() { return this.nodeName; } }); </code></pre> <p>Now given a simple object like this</p> <pre><code>var tree={ nodeName:'frumious', nodeType:'MyNode' } </code></pre> <p>I can make the object appear to be an instance of the desired nodeType with</p> <pre><code>$.extend(tree, eval(tree.nodeType+'.prototype')); </code></pre> <p>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 <a href="https://stackoverflow.com/questions/9002103/binding-objects-parsed-from-json-to-classes?answertab=votes#9002258">Rob W</a> for suggesting <code>window[tree.nodeType].prototype</code> as a better alternative)</p> <p>Now I can do things like <code>alert(tree.getName());</code></p> <h2>Better ways?</h2> <p>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...</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload