marionette.component
marionette.component copied to clipboard
How to add a loading view to a component?
I'm trying to fetch a collection before rendering my component, and would like to initially render a loading view within the component's region until the fetch is complete, and then finish by rendering the component's view. Is this possible to accomplish with Marionette.Component? I've got a loading view ready to use, and have been experimenting with the onBeforeShowView callback, but I'm stuck on how to proceed from here.
Thanks for any advice you may be able to provide! :)
Hey, @dnewkerk. I wouldn't say this is something that should work directly out of the box.
However, without trying it out, I wonder if it would work if you initially rendered your loading view, fetched your data, and then swapped out the view when loaded.
Something like:
var LoadingView = Mn.ItemView.extend(...);
var DataView = Mn.ItemView.extend(...);
var MyComponent = Mn.Component.extend({
viewClass: LoadingView,
onShow() {
this._fetchData().then(() => this._swapViews());
},
_fetchData() {...},
_swapViews() {
this._oldView = this.view;
this.view = new DataView();
// unbind events on the loading view before displaying the new view...
this.region.show(this.view);
}
});
var myRegion = new Mn.Region({ el: '#main' });
var myComponent = new MyComponent();
myComponent.showIn(myRegion);
One caveat is that you will need to handle unbinding events that were registered on the loading view when the components was first displayed. This might work. I'm open to ideas for simplifying the API to allow this. One piece that might help guide something like this is the work being done at #46.