获取集合与解析其关联模型的关系

时间:2015-06-27 17:53:48

标签: json backbone.js

当一个人在BackboneJS集合上调用fetch()时,为什么以及如何调用模型中的parse()?我基本上有 Board 集合和模型,还有 List 集合和模型。 列表属于主板。我希望将列表作为JSON数据发送到 Board 模型(例如,当调用“GET”请求时);但是,我不想在获取集合时将列表作为JSON数据发送。

我的理解是,对集合调用fetch会执行以下步骤(从不浏览模型,更不用说模型上的parse()了):

  控制器中的

index操作 - >将JSON /数据发送到Backbone - >该集合接收此数据并存储

我有一系列有相关模型的电路板:

主席 收藏

TrelloClone.Collections.Boards = Backbone.Collection.extend({
  url: '/api/boards',

  model: TrelloClone.Models.Board
});

TrelloClone.Collections.boards = new TrelloClone.Collections.Boards();

主席 模型

TrelloClone.Models.Board = Backbone.Model.extend({
  urlRoot: '/api/boards',

  lists: function() {
    if(!this._lists) {
        this._lists = new TrelloClone.Collections.Lists([], {board: this});
    }
    return this._lists;
  },

  parse: function(response) {
    console.log("parsing");
    if(response.lists) {
        console.log("inside lists");
        this.lists().set(response.lists);
        delete response.lists;
    }
  }
});

基本上,对于特定的 Board 模型,我会向该委员会寄回“清单”:

#in the boards controller
def show
  @board = Board.includes(:members, lists: :cards).find(params[:id])

  if @board.is_member?(current_user)
    render :show
  else
    render json: ["You aren't a member of this board"], status: 403
  end
end

...

#in the JBuilder file...
json.extract! @board, :title

json.lists @board.lists do |list|
    json.extract! list, :title, :ord 

    json.cards list.cards do |card|
        json.extract! card, :title, :done
    end
end

另一方面,对于 Board 集合,我不会发回“列表”:

def index
  @boards = current_user.boards
  render json: @boards
end

上述实现的问题是,当我fetch() Board 集合时,每个Board对象的属性都不会被发送。但是当我注释掉parse()函数时,一切正常。

编辑: 我弄清楚为什么我没有获取集合提取的数据。我在return response函数的末尾忘了parse。如果有人能够澄清在获取集合时发生的步骤顺序(在此序列中解析发生的位置),那将是很好的。谢谢!

1 个答案:

答案 0 :(得分:1)

查看Backbone的注释来源。

获取数据时,Backbone会设置{reset: false}或重置{reset: true}集合值。然后它调用您的成功回调,最后触发sync

http://backbonejs.org/docs/backbone.html#section-133

collection.set中,您可以确切地看到调用model.parse方法的时间以及您必须返回响应的原因:

http://backbonejs.org/docs/backbone.html#section-109

相关问题