javascript – 将JSON映射到backbone.js集合

好吧,看起来我需要一个暗示指向正确的方向.这个问题分为两部分 – 使用 JSON的多维 JSON和集合集合.

背景

我有一些JSON将从服务器检索并控制如何格式化.

多维JSON

我在将模型连接到JSON中的部件时遇到了一些麻烦.假设我想渲染每个帖子的作者姓名,以及下面的示例JSON中的状态内容.我没有问题将状态转换为模型,但作者名称我有点困惑如何去做它.根据我的理解,我必须覆盖解析.

这是不好的标准/我应该使用更好的JSON结构吗?保持尽可能平坦会更好吗?那是将作者姓名和照片提升一级吗?

我正在阅读How to build a Collection/Model from nested JSON with Backbone.js,但对我来说仍然有点不清楚.

集合中的集合

有没有一种很好的方法在backbone.js的集合中创建一个集合?我将收集一些帖子,然后就该帖子收集评论.因为我在骨干方面的发展甚至可能吗?

根据我在Backbone.js Collection of CollectionsBackbone.js Collection of Collections Issue的理解,它看起来像这样?

var Comments = Backbone.Model.extend({
    defaults : {
      _id : "",text : "",author : ""
    }
})

var CommentsCollection = Backbone.Collection.extend({ model : Comments })

var Posts = Backbone.Model.extend({
    defaults : {
        _id : "",author : "",status : "",comments : new CommentsCollection
    }
})

var PostsCollection = Backbone.Collection.extend({ model : Posts })

示例JSON

{
"posts" : [
    {
        "_id": "50f5f5d4014e045f000002","author": {
            "name" : "Chris Crawford","photo" : "http://example.com/photo.jpg"
        },"status": "This is a sample message.","comments": [
                {
                    "_id": "5160eacbe4b020ec56a46844","text": "This is the content of the comment.","author": "Bob Hope"
                },{
                    "_id": "5160eacbe4b020ec56a46845",{
                ...
                }
        ]
    },{
        "_id": "50f5f5d4014e045f000003","status": "This is another sample message.","comments": [
                {
                    "_id": "5160eacbe4b020ec56a46846",{
                    "_id": "5160eacbe4b020ec56a46847",{
    ...
    }
]}

我甚至欣赏任何提示给我的提示.谢谢!

解决方法

在尝试编写代码以使其适用于嵌套对象时,它可能会令人难以招架.但是为了简化它,可以将它分解成更小的可管理部分.

我想在这些方面.

集合

Posts
 Comments

楷模

Post
 Comment
 Author
Main collection --  Posts collection
                    (Which contains list of Post Models)

Posts集合中的每个模型都有3组属性(可能不是正确的术语).

第一级属性(status,id).

2nd – 作者属性,可以放在单独的模型(Authod模型)中.

3rd – 每个帖子模型的评论集合.

集合中的集合在这里会有点混乱.
正如你在Collection中的模型(帖子模型里面的帖子集合)和每个模型将再次嵌套一个集合(Post模型中的评论集合).基本上你会在模型中处理一个集合.

From my understanding I have to override the parse.

Is this bad standards / is there a better JSON structure I should use?

在Parse方法中处理此处理是一个非常合理的解决方案.初始化Collection或Model时,首先调用Parse方法,然后调用initialize.因此,处理Parse方法中的逻辑是完全合乎逻辑的,并且它根本不是一个糟糕的标准.

Would it be better to keep it as flat as possible?

我不认为将这个单元保持在一个单一级别是一个好主意,因为首先不需要在第一级别的其他数据.

所以我解决这个问题的方法是在Post Model中编写parse方法来处理响应,并将作者模型和Comments集合直接附加在Model上,而不是模型上的属性,以保持属性hash clean包含1st发布数据的级别.从长远来看,我认为这将更清洁,更具可扩展性.

var postsObject = [{
    "_id": "50f5f5d4014e045f000002","author": {
        "name": "Chris Crawford","photo": "http://example.com/photo.jpg"
    },"comments": [{
        "_id": "5160eacbe4b020ec56a46844","author": "Bob Hope"
    },{
        "_id": "5160eacbe4b020ec56a46845","author": "Bob Hope"
    }]
},{
    "_id": "50f5f5d4014e045f000003","author": {
        "name": "Brown Robert","comments": [{
        "_id": "5160eacbe4b020ec56a46846",{
        "_id": "5160eacbe4b020ec56a46847","author": "Bob Hope"
    }]
}];

// Comment Model
var Comment = Backbone.Model.extend({
    idAttribute: '_id',defaults: {
        text: "",author: ""
    }
});

// Comments collection
var Comments = Backbone.Collection.extend({
    model: Comment
});

// Author Model
var Author = Backbone.Model.extend({
    defaults: {
        text: "",author: ""
    }
});

// Post Model
var Post = Backbone.Model.extend({
    idAttribute: '_id',defaults: {
        author: "",status: ""
    },parse: function (resp) {
        // Create a Author model on the Post Model
        this.author = new Author(resp.author || null,{
            parse: true
        });
        // Delete from the response object as the data is
        // alredy available on the  model
        delete resp.author;
        // Create a comments objecton model 
        // that will hold the comments collection
        this.comments = new Comments(resp.comments || null,{
            parse: true
        });
        // Delete from the response object as the data is
        // alredy available on the  model
        delete resp.comments;

        // return the response object 
        return resp;
    }
})
// Posts Collection 
var Posts = Backbone.Collection.extend({
    model: Post
});

var PostsListView = Backbone.View.extend({
    el: "#container",renderPostView: function(post) {
        // Create a new postView
        var postView = new PostView({
            model : post
        });
        // Append it to the container
        this.$el.append(postView.el);
        postView.render();
    },render: function () {
        var thisView = this;
        // Iterate over each post Model
        _.each(this.collection.models,function (post) {
            // Call the renderPostView method
            thisView.renderPostView(post);
        });
    }
});


var PostView = Backbone.View.extend({
    className: "post",template: _.template($("#post-template").html()),renderComments: function() {
        var commentsListView = new CommentsListView({
            // Comments collection on the Post Model
            collection : this.model.comments,// Pass the container to which it is to be appended
            el : $('.comments',this.$el)
        });
        commentsListView.render();        
    },render: function () {
        this.$el.empty();
        //  Extend the object toi contain both Post attributes
        // and also the author attributes
        this.$el.append(this.template(_.extend(this.model.toJSON(),this.model.author.toJSON()
       )));
       // Render the comments for each Post
       this.renderComments();
    }
});

var CommentsListView = Backbone.View.extend({
    renderCommentView: function(comment) {
        // Create a new CommentView
        var commentView = new CommentView({
            model : comment
        });
        // Append it to the comments ul that is part
        // of the view
        this.$el.append(commentView.el);
        commentView.render();
    },render: function () {
        var thisView = this;
        // Iterate over each Comment Model
        _.each(this.collection.models,function (comment) {
            // Call the renderCommentView method
            thisView.renderCommentView(comment);
        });
    }
});


var CommentView = Backbone.View.extend({
    tagName: "li",className: "comment",template: _.template($("#comment-template").html()),render: function () {
        this.$el.empty();
        this.$el.append(this.template(this.model.toJSON()));
    }
});

// Create a posts collection 
var posts = new Posts(postsObject,{parse: true});

// Pass it to the PostsListView
var postsListView = new PostsListView({
    collection: posts
});
// Render the view
postsListView.render();

Check Fiddle

相关文章

事件冒泡和事件捕获 起因:今天在封装一个bind函数的时候,发现el.addEventListener函数支持第三个参数...
js小数运算会出现精度问题 js number类型 JS 数字类型只有number类型,number类型相当于其他强类型语言...
什么是跨域 跨域 : 广义的跨域包含一下内容 : 1.资源跳转(链接跳转,重定向跳转,表单提交) 2.资源...
@ "TOC" 常见对base64的认知(不完全正确) 首先对base64常见的认知,也是须知的必须有...
搞懂:MVVM模式和Vue中的MVVM模式 MVVM MVVM : 的缩写,说都能直接说出来 :模型, :视图, :视图模...
首先我们需要一个html代码的框架如下: 我们的目的是实现ul中的内容进行横向的一点一点滚动。ul中的内容...