backbone:集合和视图渲染

时间:2013-08-15 15:33:38

标签: backbone.js backbone-views

我真的很困惑这个并需要帮助。 (不相关:“现在大约需要36个小时来完成某些事情,最后一部分只是让我变得疯狂”)

我的代码

 <body>
<div id="mycontainer" style="margin: 20px; ">
</div>

<script type="text/template" id="Myelement_template">
    <% _.each( results, function( item, i ){ %>
            <div id="Myelement" style="width: 200px; height:325px; padding: 10px; background-color: #2980b9;">
                <div id="image" style="width: 190px; height: 200px; margin: auto; background-color: #f1c40f;">
                    <img src="<%= item.get('category').url %>" style="max-width: 90%;margin-top: 10px;">
                </div>
                <div id="type" style="float:left;width: 90px; height: 25px; margin-left: 5px;margin-top: 5px;background-color: #f1c40f;">
                    <%= item.get("category").type %>
                </div>
                <div id="name" style="float:left;width: 90px; height: 25px; margin-left: 10px; margin-top: 5px;background-color: #f1c40f;">
                    <%= item.get("category").name %>
                </div>
            </div>                    
        <% }); %>
</script>

<script type="text/javascript">

 $(document).ready(function() {

CategoryModel = Backbone.Model.extend({
    defaults: {
        url: '',
        type: '',
        name: ''
    }
});

MyListModal = Backbone.Model.extend({
    url: 'myrestapi',
    defaults: {
        category: CategoryModel
    }
});

MyElementView = Backbone.View.extend({
      initialize: function() {
        _.bindAll(this, 'render'); // bind 'this' in 'render'
        this.model = new MyListModal();
        this.model.bind('change', this.render);
        this.model.fetch(this.render);
     },
    el: $("#mycontainer"),
    render: function(){
        console.log(this.model.get("category"));
    }
});

 var myModelView = new MyElementView();
});
 </script>

问题

我的rest api将返回许多BaseModel对象。所有这些都需要渲染。我该怎么做?

  1. 的console.log(this.model.get( “类别”)); - 代码到达这里。不打印。调试显示已经进行了休息api调用并且已经返回了cata
  2. 如何呈现所有返回的元素?
  3. rest API返回的示例数据

    [
    {
        "category": {
            "id": 1,
            "name": "name1",
            "type": "mytype1",
            "url": "myurl1"
        },
        "user": {
            "id": 153
        },
        "status": 1
    },
    {
        "category": {
            "id": 1,
            "name": "name2",
            "type": "type2",
            "url": "url2"
        },
        "user": {
            "id": 153
        },
        "status": 1
    },
    ]
    

0 个答案:

没有答案