主干模型.未设置不删除属性

Backbone model.unset not removing property

本文关键字:删除 属性 设置 模型      更新时间:2023-09-26

我不确定为什么model.unset()事件没有触发。

我正在根据输入模糊事件设置模型的视图。 当输入具有值时,将使用值设置模型。 如果该值从表单中删除,我想从模型中删除该属性,但我的model.unset()不起作用,我不确定为什么。

这是我目前使用骨干的代码

.JS:

var TheModel = Backbone.Model.extend({    
});
var theModel = new TheModel();
var TheFormView = Backbone.View.extend({
    el: '.js-form',
    initialize: function() {
        this.model = theModel; 
    },
    template: _.template( $('#form-template').html() ),
    render: function() {
        this.$el.html( this.template({settings: this.model.toJSON()}) );
        return this;
    },
    events: {
        'blur .js-input': 'updateModel'  
    },
    updateModel: function(e) {
        var name = e.target.name,
            value = e.target.value;
        if (value !== '') {
            this.model.set(name, value);
        }
        // Why does unset not get fired here? 
        else if ( this.model.has(name) && this.model.get(name) === '' ) {
            this.model.unset(name);   
        }
    }
});
var TheOutputView = Backbone.View.extend({
    el: '.js-output',
    initialize: function() {
        this.model = theModel;  
        this.listenTo(this.model, 'change', this.render);
    },
    template: _.template( $('#output-template').html() ),
    render: function() {
        this.$el.html( this.template({settings: this.model.toJSON()}) );
        return this;
    },
});
var theFormView = new TheFormView();
theFormView.render();
var theOutputView = new TheOutputView();
theOutputView.render();

网页和模板:

<div class="js-form">
</div>
<div class="js-output">
</div>
<script type="text/template" id="form-template">
    <h1>Form</h1>
    <form action="" method="Post">
        <div>
            <label for="firstName">First Name:</label>
            <input type="text" class="js-input" id="firstName" name="f_Name" />
        </div>
        <div>
            <label for="lastName">Last Name:</label>
            <input type="text" class="js-input" id="lastName" name="l_Name" />
        </div>
    </form>
</script>
<script type="text/template" id="output-template">
    <div>
        f_Name = <%- settings.f_Name %>
        <br />
        l_Name = <%- settings.l_Name %>
    </div>
</script>

您有一个简单的逻辑错误 - 您不应该在检查中包含this.model.get(name) === ''

实际上,前面if意味着不能将模型的 name 属性设置为空字符串。因此,除非可以在应用程序的其他位置将其设置为空字符串,否则永远无法满足else if条件。

这应该按您的预期工作:

if (value !== '') {
  this.model.set(name, value);
}
else if ( this.model.has(name)) {
  this.model.unset(name);   
}