簡體   English   中英

如何解析此JSON以用於Backbone View

[英]How can I parse this JSON for use in Backbone View

我正在嘗試學習Backbone,似乎無法將fetch功能中的數據與我的Underscore模板相匹配。 如何在JSON中獲取子數組並將其與模板匹配?

Backbone.View看起來像這樣:

var Projects = Backbone.Collection.extend({
    url: '/tree/projects'
});

var Portfolio = Backbone.View.extend({
    el: '.page',
    render: function () {
        var that = this;
        var projects = new Projects();
        projects.fetch({
            success: function (projects) {
                var template = _.template($('#projects-template').html());
                that.$el.html(template({projects: projects.models}));
            }
        })
    }
});

在網址: http://localhost:3000/portfolio/api/tree/projects

返回的JSON如下所示:

{  
   id:"projects",
   url:"http://localhost:8888/portfolio/projects",
   uid:"projects",
   title:"Projects",
   text:"",
   files:[  

   ],
   children:[  
      {  
         id:"projects/example-1",
         url:"http://localhost:8888/portfolio/projects/example-1",
         uid:"example-1",
         title:"Example 1",
         images:"",
         year:"2017",
         tags:"Website",
         files:[  

         ],
         children:[  

         ]
      },
      {  
         id:"projects/example-2",
         url:"http://localhost:8888/portfolio/projects/example-2",
         uid:"example-2",
         title:"Example @"2
         text:"Example 2's text",
         year:"2016",
         tags:"Website",
         files:[  
            {  
               url:"http://localhost:8888/portfolio/content/1-projects/4-example-2/example_ss.png",
               name:"example_ss",
               extension:"png",
               size:244845,
               niceSize:"239.11 kB",
               mime:"image/png",
               type:"image"
            }
         ],
         children:[  

         ]
      },
   ]
}

我的Underscore文件如下所示:

<script type="text/template" id="projects-template">
<h4>tester</h4>
<div>
    <% _.each(projects.children, function (project) { %>
    <div>
        <div><%= project.get('year') %></div>
        <div><%= project.get('title') %></div>
        <div><%= project.get('tags') %></div>
    </div>
    <% }); %>
</div>
</script>

您可以在集合上定義解析方法:

var Projects = Backbone.Collection.extend({
  url: '/tree/projects',
  parse: function(response){
    /* save other data from response directly to collection if needed.
     for eg this.title = response.title; */
    return response.children; // now models will be populated from children array
  }
});

不要使用parse

雖然我通常同意TJ ,但對集合使用解析更像是一個黑客而不是一個明確的解決方案。 它只能用於獲得項目的子項目,僅此而已。

parse函數不應該對集合產生副作用,使用這種方法,不容易在父項目上更改和保存字段。

它也沒有處理它是嵌套結構的事實,它不僅僅是一個包裝數組。

接收包裝數據時,此功能最有效:

{
    data: [{ /*...*/ }, { /*...*/ }]
}

模型和收藏品

你在這里什么是嵌套項目 的項目 項目應該是一個模型。 你也有文件,所以你應該有一個File模型。

獲取每個資源並使用它創建模型和集合類。 但首先,將共享數據排除在外。

var API_ROOT = 'http://localhost:8888/';

文件

var FileModel = Backbone.Model.extend({
    defaults: {
        name: "",
        extension: "png",
        size: 0,
        niceSize: "0 kB",
        mime: "image/png",
        type: "image"
    }
});

var FileCollection = Backbone.Collection.extend({
    model: FileModel
});

項目

var ProjectModel = Backbone.Model.extend({
    defaults: function() {
        return {
            title: "",
            text: "",
            files: [],
            children: []
        };
    },
    getProjects: function() {
        return this.get('children');
    },
    setProjects: function(projectArray, options) {
        return this.set('children', projectArray, options);
    },

    getFiles: function() {
        return this.get('files');
    },
    getSubProjectUrl: function() {
        return this.get('url');
    }
});

var ProjectCollection = Backbone.Collection.extend({
    model: ProjectModel,
    url: API_ROOT + '/tree/projects'
});

項目視圖

然后,查看項目。 這是一個簡單的示例,請參閱有關優化渲染的提示的其他信息。

var ProjectView = Backbone.View.extend({
    template: _.template($('#projects-template').html()),
    initialize: function(options) {
        this.options = _.extend({
            depth: 0, // default option
        }, options);

        // Make a new collection instance with the array when necessary
        this.collection = new ProjectCollection(this.model.getProjects(), {
            url: this.model.getSubProjectUrl()
        });
    },

    render: function() {
        this.$el.html(this.template(this.model.toJSON()));
        this.$projectList = this.$('.list');

        // use the depth option to avoid rendering too much projects
        if (this.depth > 0) this.collection.each(this.renderProject, this);
        return this;
    }

    renderProject: function(model) {
        this.$projectList.append(new ProjectView({
            model: model,
            depth: depth - 1
        }).render().el);
    }
});

使用這樣的模板:

<script type="text/template" id="projects-template">
    <h4><%= title %></h4>
    <span><%= year %></span><span><%= tags %></span>
    <p><%= text %></p>
    <div class="list"></div>
</script>

使用視圖:

var model = new ProjectModel({ id: "project" });
model.fetch({
    success: function() {
        var project = new ProjectView({
            model: model,
            depth: 2
        });
    }
});

附加信息

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM