0

I am looking for the best way to trigger an event when the fetch is completed.
This code works but I am curious to know if there is a better way to accomplish the following task.

var myApp = new Marionette.Application();

myApp.on("initialize:before", function () {
    this.currentUser = new UserModel();
    this.currentUser.fetch({
        complete: function () {
            myApp.vent.trigger('currentUser');
        }
    });
});
Lorraine Bernard
  • 13,000
  • 23
  • 82
  • 134

1 Answers1

2

A successful fetch triggers a "change" event:

fetch model.fetch([options])

[...] A "change" event will be triggered if the server's state differs from the current attributes.

So if the fetch does anything, there will be a "change" that you can listen for:

myApp.on("initialize:before", function () {
    this.currentUser = new UserModel();
    this.currentUser.on('change', function() {
        myApp.vent.trigger('currentUser');
    });
    this.currentUser.fetch();
});

That will also trigger a "currentUser" event if this.currentUser is changed in some other way and that might or might not be what you want. If you only want your function called once then your current success handler is probably the easiest thing to do; you could still use on and unbind the handler when it is called:

myApp.on("initialize:before", function () {
    var triggerCurrentUser = _.bind(function() {
        myApp.vent.trigger('currentUser');
        this.currentUser.off('change', triggerCurrentUser);
    }, this);

    this.currentUser = new UserModel();
    this.currentUser.on('change', triggerCurrentUser);
    this.currentUser.fetch();
});

You could also use _.once but that would leave a no-op callback function kicking around and there's no need for that.

mu is too short
  • 426,620
  • 70
  • 833
  • 800
  • Actually I want my function called once when the model is fetched and not when it changes. So at this point what is the advantage to use `off `? Is it more recommendable than using a callback? – Lorraine Bernard Jun 27 '12 at 22:54
  • @LorraineBernard: Your current `success` handler is fine if you just want a one-shot callback. You'd usually only use `on` if you wanted multiple notifications or if the `this.currentUser.on()` and `this.currentUser.fetch()` were in different places in the source (i.e. using `success` wouldn't work due to state information being somewhere else). – mu is too short Jun 27 '12 at 22:59