0

I had a model and view, where view is rendering before the model is fetching the data. When i checked in the DB, the value is persisting to DB when i make changes in the view. But I am unable to get the value through model.fetch() while view is rendering.

define([
    "marionette",
    "monet",
    "modules/fetchParams/collections/fetchParamsListLevels",
    "modules/fetchParams/views/fetchParamsLayoutView",
    "modules/fetchParams/models/fetchParam"
], function(Marionette, Monet, fetchParamListLevels, FetchParamsLayoutView,FetchParamModel){
    return Marionette.Module.extend({
        model:"",
        onStart:function(){
            this.model =new FetchParamModel();
        },
        displayInRegionMarketParams:function(region){
           this.fetchModel("market");
           region.show(new FetchParamsLayoutView({model: this.model, title: " Market"}));
        },
       displayInRegionShareParams:function(region){
           this.fetchModel("shares");
           region.show(new FetchParamsLayoutView({model: this.model, title: "Shares"}));
        },
.
.
.
fetchModel:function(type){
            this.model.setType(type);
            this.model.fetch();
        }

I tried as below but not able to find solution. Let me know what i am missing here.

this.listenTo(this.model, "change", this.render()); 
CNKR
  • 568
  • 5
  • 19

1 Answers1

0

It looks like you accidentally added parentheses to your this.render callback. The point of a callback is that it will be called for you, so you don't have to. So you pass it without parentheses to the event listener, and it will run it for you.

Your code will work this way:

this.listenTo(this.model, "change", this.render);

Also if you would like to perform anything just after the data came from the server, you might use the promise that is returned from the fetch() method:

this.model.fetch().done(function(data, status, xhr){
  console.log( data, status, xhr );
  /** update the view maybe */
});
Yura
  • 2,690
  • 26
  • 32
  • Thanks for your inputs . I had a doubt regarding model.fetch(), after model.fetch() completes , is it automatically set value to the model. One more thing i tried to put my region inside the success callback of fetch, there is problem with the region as "region as undefined" – CNKR Nov 08 '15 at 16:21
  • Yes, `model.fetch()` automatically sets new data to the model, so you can listen to the change with `listenTo` as in the first part of my answer. – Yura Nov 08 '15 at 16:22
  • Also region may happen to be undefined, because you lose context, which means `this` isn't the same object instance anymore. – Yura Nov 08 '15 at 16:36