Marionette ItemView how to re-render model on change

34,358

Solution 1

Actually, Backbone and Marionette are smart enough to do it.
Problem was in template and data as I found it another question. So, I re-checked everything and got result.

Solution 2

In the View, You can use following code

    modelEvents: {
        'change': 'render'
    }

instead of

   initialize: function () {
        this.model.on('change', this.render, this);
    },
    onRender: function () {
        console.log(this.model.toJSON());
     }
Share:
34,358
Vadim Ivanov
Author by

Vadim Ivanov

Lead Software Engineer, M.Sc. in C.S., 11 yrs in the industry. Team lead with successful experience of building the team to solve business challenges. Performance focused, beautiful solutions-driven, maintainability oriented. I am very much into web development and making web services optimized, fast and scalable. Organized, a self-driven person with strong motivation for personal and professional skills development. I throw myself into projects, take responsibility and consistently meet deadlines. Keywords: Java, Go Lang, Open Street Maps, Node.js, Apache Kafka, Docker, AWS services, Postgresql, DynamoDB, Open API (Swagger), Git, Agile.

Updated on August 30, 2020

Comments

  • Vadim Ivanov
    Vadim Ivanov over 3 years

    I'm using Handlebars template engine.
    so, I have Model:

    Backbone.Model.extend({
            urlRoot: Config.urls.getClient,
            defaults: {
                contract:"",
                contractDate:"",
                companyTitle:"",
                contacts:[],
                tariff: new Tariff(),
                tariffs: [],
                remain:0,
                licenses:0,
                edo:""
            },
            initialize:function(){
                this.fetch();
            }
        });
    

    then Marionette ItemView:

    Marionette.ItemView.extend({
            template : templates.client,
            initialize: function () {
                this.model.on('change', this.render, this);
            },
            onRender: function () {
                console.log(this.model.toJSON());
             }      
        });
    

    and then I call everything as:

    new View({
        model : new Model({id:id})
            })
    

    and, it's immediately render a view for me and this is cool. But after the model fetched data it's trigger "change", so I see in console serialised model twice, and I see for first time empty model and then filled one.

    But, the view is NOT updated.

    How I can fix it?

    P.S. I understand, that I can call a render method on fetch done callback. But I also need it for further actions, when user will change model.