locked
Getting function in WinJS namespace from String

    Question

  • I have persisted my objects to JSON and want to construct the object from JSON again later. For that I write the name of the object construction function into the JSON serialization like this: "com.acme.Picture"

    Now when I read back the JSON I would like to construct the Picture object again. In plain javascript I would use

    window["Picture"]

    to get the function, but since I used WinJS namespaces, the window object does not hold a property named "com.acme.Picture".

    Question is: How do I get a function from the namespace?

    Monday, February 6, 2012 11:55 AM

Answers

  • toObject: function(json) {
          var fn, part, _i, _len, _ref;
          _ref = (json.className || this.className).split('.');
          for (_i = 0, _len = _ref.length; _i < _len; _i++) {
            part = _ref[_i];
            fn = (fn != null ? fn[part] : void 0) || window[part];
          }
          return typeof fn === "function" ? new fn(json) : void 0;
        }
    

    I solved this using this code ;)
    Monday, February 6, 2012 1:57 PM