Render a Marionette region after model has been fetched
Asked Answered
O

2

5

I would like to use the approach described by Derick Bailey in "A Generic Problem Solution" in this thread to render a view after a model is fetched. I will report his solution here:

 MyView = Backbone.View.extend({
  initialize: function(){
    this.model.on("sync", this.render, this);
  },

  render: function(){ ... }
});


myModel = new MyModel({id: someId});
new MyView({
  model: myModel
});

myModel.fetch();

I have a slightly different situation: my view is inside a region layout. If I call the Marionette.Region.show() it works but the view is rendered twice. Calling Marionette.Region.attachView() the view render's function is called once but the content is not displayed in the page.

Any idea?

Obligee answered 19/3, 2013 at 11:6 Comment(1)
If you use Marionette Regions and Views, the view will updated every time the model changes. So if you only want the view to render once, you will have to fetch the model before you call the show method on the region.Balladry
U
13

You can wait until the model is sync'd before rendering the view


var myView = new MyView({
  model: myModel
});

myModel.on("sync", function(){
  myRegion.show(myView);
});

myModel.fetch();
Unicuspid answered 19/3, 2013 at 19:23 Comment(0)
A
4

I have come up with a slightly different approach. I neede my views to load their own models on initalize, so Derick's approach was not really working for me. There were several reasons which I don't want to explain here. But I came was this:

I created a default template called with loading indicator and spinner, which I attach to template of the view. I have a method called updateView, which is triggered once the model syncs and replaces the loading template with real template and calls render() afterwards.

Maybe someone will also find it useful.

var myView = new MyView({
     template: loader,
     initialize : function(){
        this.model = new MyModel();
        this.model.on("sync", this.updateView, this);
        this.model.fetch();
     },
     updateView : function(){
        this.template = myTemplate;
        this.render();
     }
});
Ainslie answered 19/7, 2013 at 14:1 Comment(2)
Hmm, what would happen if the fetch completes during the rendering phase (in between the render, show, attach events)? Wouldn't it cause weird issues, like the view being attached to the DOM twice, or multiple event handlers?Valeta
Since javascript is single threaded, the rendering and event binding will finish before another can be triggered.Ainslie

© 2022 - 2024 — McMap. All rights reserved.