Why resetting a form does not clear the bound model attributes

191 views Asked by At

I have bound the text inputs in a form to a Backbone Model using backbone-stickit bindings:

bindings: {
    '#txtRemarks': 'remarks',
    '#txtFromAccountNumber': 'account_no',
    '#fileChooser':'fileChooser'
}

When I reset the form, the values in the text inputs are getting cleared, but the values are still present in the model attributes.

1

There are 1 answers

0
Emile Bergeron On

Stickit default handler for input elements is (source):

{
    selector: 'input',
    events: ['propertychange', 'input', 'change'],
    update: function($el, val) { $el.val(val); },
    getVal: function($el) {
        return $el.val();
    }
}

It listens to 'propertychange', 'input', 'change' and a form reset doesn't trigger these events.

You will need to manually listen to the reset event of the form and update the model manually.

var FormView = Backbone.View.extend({
    bindings: { /* ... */ },
    events: {
        '#form-id reset': 'onReset',
    },
    ui: {
        remarks: '.remarks-input',
        account: '.account-input'
    },

    onReset: function(e) {
        this.model.set({
            remarks: this.getUI('remarks').val(),
            account: this.getUI('account').val(),
        });
    }
});

Or another trick when dealing with forms is to keep a copy of the model in its initial state, before doing any change. Then you can use the copy to reset the attributes or to check if there were changes.

var FormView = Backbone.View.extend({
    bindings: { /* ... */ },
    events: {
        '#form-id reset': 'onReset',
    },
    initialize: function() {
        this.master = this.model.clone();
    },

    onReset: function(e) {
        this.model.set(this.master.attributes);
    },
    getChanges: function() {
        return this.master.changedAttributes(this.model.attributes);
    },
    isDirty: function() {
        return Boolean(this.getChanges());
    },
});