【问题标题】:How can I unset an attribute when the value is empty?当值为空时如何取消设置属性?
【发布时间】:2013-10-28 19:54:10
【问题描述】:

我有一个包含许多空字段的搜索表单。用户在字段中输入值并点击“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') 对空属性的处理?
  • 我没有,因为我不确定最有效和无缝的地方。

标签: javascript backbone.js marionette backbone-stickit


【解决方案1】:

在这种情况下,我只需将输入修复为 $.param:

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

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

$.param(params);

Underscore 上似乎没有合适的实用程序,但可以很容易地提供类似于here 所述的实用程序。

【讨论】:

    【解决方案2】:

    我在制作项目时遇到了类似的问题,对我来说_.defaults 工作,但也许在你的情况下,你可以使用过滤器、减少或任何其他下划线函数之一。

    【讨论】:

      猜你喜欢
      • 2012-03-10
      • 2016-02-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-19
      • 2016-08-29
      • 1970-01-01
      • 2012-11-12
      相关资源
      最近更新 更多