Instead of focusing in the model event, we can focus on the view life cycle. For that purpose, Marionette makes the onBeforeDestroy
callback available on Marionette.View (which is extended by all Marionette views). In your ItemView you'd define the callback like this
onBeforeDestroy: function () {
$('#myElement').animate({ "height" : "0", 1000 });
}
They're is an important caveat here. Since $.animate
is an asynchronous function, it is possible that the view may be removed before $.animate
finishes the transition. So, we have to make a modification to our onBeforeDestroy
.
onBeforeDestroy: function () {
var animationDelay = 1000ms;
this.remove = _.delay(_.bind(this.remove, this), animationDelay );
this.$el.animate({ "height" : "0", animationDelay });
}
Essentially, what we did here is set the View.remove()
method to fire after the animation has run through, ensuring that when this.remove
is called, it's called asynchronously, after the animation has run through. You could also do this with Promises, I suppose, but that requires a bit more overhead.