BackboneJS在视图中呈现视图

时间:2014-03-13 13:59:08

标签: json backbone.js recursion view nested

我无法理解我应该非常基本的东西。我确信我所需要的只是单行答案,希望能让一切变得有价值! :)在有人询问之前,是的,我花了48个多小时试图解决它,阅读无数文章,但似乎没有什么真正击中头部,所以我真的很感激帮助。

我想要构建的是一个相对简单的决策树图,其中任何节点都不会有两个以上的可能结果。

我最初的想法很简单:我有一个模板:

<script type="text/template" id="answer-template">
   <section class="outerbox">
        <article class="first_line" id="first_line_<%- id %>">
            <label><%- text %></label>
        </article>
        <article class="second_line" id="second_line_<%- id %>">
            <div class="second_line_left" id="second_line_left_<%- id %>">
                <!-- append this for no answer //-->
            </div>
            <div class="second_line_right" id="second_line_right_<%- id %>">
                <!-- append this for yes answer //-->
            </div>
        </article>
   </section>
</script>

并且尽可能简单地说,我想要的是这个模板以递归方式附加在secoond_line_left和second_line_right div框中。

我将收到的JSON类型将是:

{ "id": 1, 
  "question": "Do you like JavaScript", 
  "yes":{
          "id":2, 
          "question": "Have you tried JQuery", 
          "yes": {...}, 
          "no":{...}
  }, 
  "no":{
          "id":5, 
          "question": "Have you tried JavaScript", 
          "yes": {...}, 
          "no":{...}
  }
}

其中{...}表示将出现相同类型的格式。

所以我在视图中尝试做的事情如下:

 add_one: function(answer) {
        var view = new AnswerView({model: answer});
        $("#"+this.options.append_this).append(view.render().el);

        if(answer.attributes.yes){
          var so_yes = "second_line_right_"+answer.attributes.id;
         // here i want to call the add_one function again to append to the element
         // with id seen in the so_yes variable above, and the json inside the "yes"
         // key of the JSON currently being recursively executed
        }

        if(answer.attributes.no){
         var so_no = "second_line_left_"+answer.attributes.id;
         // here i want to call the add_one function again to append to the element
         // with id seen in the so_no variable above, and the json inside the "no"
         // key of the JSON currently being recursively executed
        }

    },

我试图通过几种不同的方式从内部调用函数,传入JSON和元素的ID ......我试图在每次进入yes或者a时重新渲染视图不,但我似乎无法这样......

有谁能请我指出正确的方向?我认为它必须是一个非常简单的单行答案?我错了吗?

感谢您的时间!

0 个答案:

没有答案