Mobx可观察到深层对象

时间:2016-10-14 03:34:35

标签: javascript json mobx

我正在寻找最佳解决方案如何在深度json对象结构(例如树)上实现@observable,数据树可能会非常深入。并且每个节点都有许多属性,但我只需要观察树节点中的一个属性。只要我这样做

@observable questionnaire = {}

它有效,但我认为这是腰部。我只需要观察'选定'属性。 这是json结构。如果我错了,请纠正我,简化问卷调查对象。

[
  {
    "id": "1",
    "title": "level 1",
    "description": "text",
    "type": "Question",
    "selected": false,
    "childNodes": [
      {
        "title": "level 2",
        "description": "text",
        "type": "Question",
        "selected": false,
        "childNodes": [
          {
            "title": "level 3",
            "description": null,
            "type": "Question",
            "selected": false,
            "childNodes": [
              {
                "title": "level 4 1",
                "childNodes": [],
                "description": null,
                "type": "Checkbox",
                "selected": false
              },
              {
                "title": "level 4 2",
                "childNodes": [],
                "description": null,
                "type": "Checkbox",
                "selected": false
              },
              {
                "title": "level 4 3",
                "childNodes": [],
                "description": null,
                "type": "Checkbox",
                "selected": false
              },
              ...
            ]
          }, ...

1 个答案:

答案 0 :(得分:1)

One way is to have a Node class implemented as follows:

class Node {
  @observable selected = false;
  @observable childNodes = asFlat([]);

  constructor(data) {
    // Recursively create `Node` objects for all children.
    data.childNodes = data.childNodes.map(child => new Node(child));
    Object.assign(this, data);
  }
}

Then you create a Node object from your top-level json object: new Node(json).

This solution will only observe selected and childNodes. It's not ideal because you need to wrap your json object in Node objects. But I can't think of any other way to do it.