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?
In this scenario I'd just fix the input to $.param:
There seems to be no proper utility available at Underscore, but could be easily provided similar to what is described here.