Backbone-relational icon indicating copy to clipboard operation
Backbone-relational copied to clipboard

Fetch models only once from server

Open bobjansen opened this issue 10 years ago • 3 comments

Sometimes a model instance (child) is related to a number of other model instances (parents). If I initialize parent-1 and parent-2 I'd like to attach the child. For the parent-1 this is not a problem, just do

var child = Child.findOrCreate({id: id});
child.Fetch();

in the initialization of the Parent-model. However if I create parent-2 I do not want to refetch (the data for the Child model changes weekly). I don't see a cleary way to do this with the current API. Therefore I'd like to propose a new option for the fetch-function: fetchOnce. If set to true (default isfalse to keep the old behavior) the model is only fetched on first call.

I can contribute a patch if this seems worthwhile.

bobjansen avatar May 30 '14 08:05 bobjansen

This doesn't really sound specific to backbone-relational? Seems more like the default backbone implementation of fetch doesn't play nice with what you're trying to achieve. In your case, I would write it more like the following:

var child = Child.find( id );
if ( !child ) {
    child = new Child({ id: id });
    child.fetch();
}

(find is an alias for findOrCreate, with the create option set to false)

PaulUithol avatar Jun 04 '14 12:06 PaulUithol

Btw, I'm also working on a better implementation for lazy loading; sounds like that may be at the core of your problem? See #467 .

PaulUithol avatar Jun 04 '14 12:06 PaulUithol

Maybe, I'm still learning. Sometimes I prefer the extra param but in other cases your solution which is a bit more verbose is more clear. I'll continue with my ad hoc solution for now and I think that as my skills and our products evolve I can better argue for inclusion of this feature or become more enlightened and come to the conclusion that it's bad. I think for now the ticket can be closed. Agreed?

bobjansen avatar Jun 18 '14 12:06 bobjansen