1

What's a clean way to run some code during initialize() if a Model is constructed with all its data, but otherwise run that code only after a fetch? The best I have is something like the following, but I'm hoping there's a more streamlined way of doing it:

if (this.hasData()) {
    this.setupListeners();
} else {
    this.fetch().done(this.setupListeners);
}

Or maybe the following, though the intent isn't super obvious when reading:

var whenLoaded = (this.hasData()) ? $.Deferred().resolve() : this.fetch();
whenLoaded.done(this.setupListeners);

Backstory: the model does some listenTo calls on itself so it can save itself when certain changes occur. But if the model needs fetching, the listenTo()s shouldn't be made until the fetch finishes, otherwise once the data is fetched the subsequent set will trigger the change events and thus an unnecessary save to the server.

Is there a cleaner way to do this? Or maybe this is as good as it gets and I'm being picky. Thanks for your thoughts.

Cameron
  • 2,276
  • 2
  • 15
  • 12
  • 1
    You mean, you are implementing auto-save within the model itself? That sounds like an anti-pattern. You've eliminated unit-of-work usability of callers that may want to make multiple changes and `save()` when appropriate for the context they're in. – Crescent Fresh Sep 13 '14 at 03:08
  • 2
    what you have looks fine to me – Vic Sep 13 '14 at 04:31
  • Listen to and use custom events on the model to save data to the server. – Eugene Glova Sep 13 '14 at 09:22
  • @CrescentFresh, yes I've implemented auto-save. I'd normally agree with you, though with this particular model I believe it makes sense because a) these attributes are only updated one at a time (with the exception of this mass fetch), and b) I debounce the save calls so if we do change several at once then only one save is executed. – Cameron Sep 15 '14 at 12:03
  • @Cameron: sounds like you've thought it out pretty thoroughly. Q: is your example code going directly into the body of the constructor? – Crescent Fresh Sep 15 '14 at 14:16
  • @CrescentFresh: yes, well the initialize() anyhow. Seem somewhat reasonable to you? – Cameron Sep 15 '14 at 18:31
  • @Cameron: only thing comes to mind is (inside `initialize`) to do: `this.once('sync', this.setupListeners, this)`. That will setup listeners after the very first fetch-and-set call is complete, thereby avoiding recursion by auto-saving on initial set and separating the concern of who is suppose to call `fetch()` in the first place. I think. – Crescent Fresh Sep 15 '14 at 20:01

0 Answers0