我有一個空字段數量的搜索表單。在用戶輸入值並輸入「Enter」後,我從值中創建一個查詢字符串(使用$.param()
)並將其發送到服務器。一切都很好,直到你清空一個區域並再次點擊「Enter」。由於該字段以前有一個值,因此該屬性已經設置好了,所以現在當點擊提交屬性時仍然將其添加到查詢字符串中,只有沒有附加值。如何在值爲空時取消設置屬性?
一個例子,有些代碼:
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);
}
});
您將在var query = $.param(this.model.attributes);
行我轉換模型的屬性的查詢字符串來跟着我的API發送看到。您也可能會看到我正在使用backbone.stickit。如何在創建查詢字符串之前無縫地取消任何空的以下的屬性?
您是否嘗試過'this.model.unset('attributeName')'屬性爲空? – fbynite
我並不是因爲我不確定最有效和無縫的地方纔能做到這一點。 –