Why does 'on change' fire when record view is loaded?

I must be missing something...

Why do on change events fire when the record view is loaded before that field is indeed changed?

How can I stop the execution of an on change until the field is actually changed?

thanks,
Francesca
  • I think when the view renders model attribute are getting set, which is a change.
    Inside the function you can give a condition like this to prevent the execution of the function body.
    if(!_.isEqual(this.model.get('<attribut>'),this.model.previous('<attribute>'))){
           //execute the function body
    }
  • Hi @FrancescaS

    Other alternative is:
    if (!_.isEmpty(this.model) && this.model.hasChanged("<field_name>")) {...}

    Regards,

    Rubén Recacha
    Consultant REDK Software Engineering
  • You can add the onchange event like this , so that this will trigger only on actual field change 

     this.model.once( "sync",
                function() {
                    this.model.on(
                        "change:{field_name}",
                        this.{function_name},
                        this
                    );                
                },
                this
            );
  • Hi All,

    @Varun Nath: This works.

    Another approach is:

    When I tried console.log(this.model.previous('<attr>')), it returns undefined which will execute the condition !_.isEqual(), so I tried this:

    if(typeof this.model.get('<attr>') !== "undefined") { // function call }
    So, now we have hand full of options to try ;)
  • I use onchange, in events like this...
    initialize: function (options) {       this._super('initialize', [options]);
            this.events['change input[name=status]'] = 'changedStatus';
        },
        changedStatus: function() {
                console.log("Status Changed new Value is : "+this.model.get('status'));
        },


    This works perfect only fires when value is changed not fire on load of page.

    Regards,
    Usman
  • This works for me:

    if(!_.isEmpty(this.model.get('contact_id_c')) && typeof(this.model.previous('contact_id_c'))!=='undefined' && !_.isEqual(this.model.get('contact_id_c'),this.model.previous('contact_id_c')))
    thank you everyone!
    FrancescaS

  • Hi Francesca,

    Just one suggestion, you can use
    _.isUndefined(this.model.previous('contact_id_c')) instead of
    typeof(this.model.previous('contact_id_c'))!=='undefined'
    as sugar team is suggesting to make use of underscore functions as much as possible during customzation!

    Thanks!