如何通过theis路径获得嵌套的Backbone模型和集合,就像JSON一样?

时间:2014-06-23 10:58:33

标签: javascript json backbone.js

我有以下JSON代表我的博客帖子数据(只是示例):

var post = {
   id: 123,
   title: 'Sterling Archer',    
   comments: [
     {text: 'Comment text', tags: ['tag1', 'tag2', 'tag3']},
     {text: 'Comment test', tags: ['tag2', 'tag5']}
   ]  
}

此JSON的每个单元都有适当的Backbone模型或集合表示:

var PostModel = Backbone.Model.extend({
   parse: function (response) {
       if (response.comments) {
          response.comments = new Backbone.Collection(response.comments, {
              model: CommentModel
          });
       }
       return response;
   }    
});

var CommentModel = Backbone.Model.extend({
    parse: function (response) {
        if (response.tags) {
          response.tags = new Backbone.Collection(response.tags);
        }
        return response;
    }  
 });

 var post = new PostModel(post, {parse: true});

我需要存储'路径'对于每个集合/模型,可以获得如下内容:

post.get('/comments/0');       // comment model: {text: 'Comment text', tags: ['tag1', 'tag2', 'tag3']}
post.get('/comments/1/tags/1') // tag model with 'tag5'

如果有可能获得模型和/或集合的绝对路径,那将是很酷的 这是使这种可怜的最佳方法吗?

1 个答案:

答案 0 :(得分:2)

您可以覆盖Backbone.Model类,添加支持绝对路径的自定义_get方法。这是覆盖代码

Backbone.Model = Backbone.Model.extend({

  _get : function(path)
  {
      if(!path)
        return;

       var array = path.split('/');
       var that = this;
       var result = that;
       _.each(array, function(o, i){
            if(o && result)
            {
                if(result instanceof Backbone.Collection)
                    result = result.at(o);
                else if(result instanceof Backbone.Model)
                    result = result.get(o);
                else if(_.isArray(result) || _.isObject(result))
                    result = result[o];
                else
                    result = undefined;
            }

       });
       return result;
  }
});

这将支持所有数据结构,如Model,Collection,Array,Object

可以使用它
post._get('/comments/0');      
post._get('/comments/1/tags/1');