When one calls fetch() on a BackboneJS collection, why and how does parse() in the model also get called? I basically have Board collection and model, and also List collection and model. A List belongs-to a Board. I want to send the List down as JSON data with a Board model (when a "GET" request is called, for instance); however, I do NOT want to send the List down as JSON data when the collection is fetched.
My understanding was that calling fetch on a collection goes through the following steps (never going through the model, let alone the parse() on the model):
indexaction in controller -> sends JSON/data to Backbone -> the collection receives this data and stores it
I have a collection of boards in that has an associated model:
Board Collection:
TrelloClone.Collections.Boards = Backbone.Collection.extend({
url: '/api/boards',
model: TrelloClone.Models.Board
});
TrelloClone.Collections.boards = new TrelloClone.Collections.Boards();
Board Model:
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;
}
}
});
Essentially, for a particular Board model, I send back "lists" with that 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
For a Board collection, on the other hand, I do not send back the "list":
def index
@boards = current_user.boards
render json: @boards
end
The problem with my above implementation is that when I fetch() the Board collection, the attributes of each Board object are not sent over. But when I comment out the parse() function, everything works fine.
EDIT: I figured out why I wasn't getting data on a collection fetch. I forgot to return response at the end of the parse function. It'd be nice if someone could clarify what exactly are the sequence of steps that occur when a collection is fetched (where the parsing happens in this sequence). Thanks!
Aucun commentaire:
Enregistrer un commentaire