Lorraine Bernard
Lorraine Bernard

Reputation: 13400

The best way to trigger an event when the model.fetch is complete

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');
        }
    });
});

Upvotes: 0

Views: 804

Answers (1)

mu is too short
mu is too short

Reputation: 434665

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.

Upvotes: 2

Related Questions