How can I unset an attribute when the value is empty?

492 views Asked by At

I have a search form with a number of empty fields. After the user enters values into the fields and hits "Enter" I create a query string from the values (using $.param()) and send that to the server. All is well, until you empty a field and hit "Enter" again. Because that field previously had a value the attribute has already been set, so now when hitting submitting the attribute is still being added to the query string, only with no value attached.

An example, and some code:

Search.CustomerCard = Marionette.ItemView.extend({
    template: "#customer-search-card",
    tagName: "section",
    className: "module primary-module is-editing",
    initialize: function () {
        this.model.on('change', function(m, v, options) {
            console.log("Changed?", m.changedAttributes();
        });
    },
    events: {
        "click .js-save": "searchCustomers",
        "keypress [contenteditable]": "searchCustomersOnEnter"
    },
    bindings: {
        …
    },
    onRender: function () {
        this.stickit();
    },
    searchCustomersOnEnter: function (e) {
        if (e.keyCode !== 13) { return; }
        e.preventDefault();
        this.searchCustomers(e);
    },
    searchCustomers: function (e) {
        e.preventDefault();
        $(e.target).blur();
        var query = $.param(this.model.attributes);
        this.trigger("customers:search", query);
    }
});

You'll see in the var query = $.param(this.model.attributes); line that I'm converting the model's attributes to a query string to send along to my API. You may also see I'm using backbone.stickit. How can I seamlessly unset any attributes that are empty before creating the query string?

2

There are 2 answers

0
Hannes Obweger On BEST ANSWER

In this scenario I'd just fix the input to $.param:

var params = _.clone(this.model.attributes);

_.each(params, function(value, key) {
    if (value == "") {
        delete params[key];
    }
});

$.param(params);

There seems to be no proper utility available at Underscore, but could be easily provided similar to what is described here.

0
dsymquen On

I ran into a similar problem when i was making my project, for me _.defaults worked, but maybe in your case, you can use one of filter, reduce or anyother underscore functions.