M Hari
M Hari

Reputation: 113

Why resetting a form does not clear the bound model attributes

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.

Upvotes: 2

Views: 195

Answers (1)

Emile Bergeron
Emile Bergeron

Reputation: 17430

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());
    },
});

Upvotes: 2

Related Questions