我不确定为什么model.unset()
事件没有被触发。
我正在根据输入模糊事件设置模型的视图。当输入具有值时,将使用该值设置模型。如果不是从表单中删除该值,我想从模型中删除该属性,但我的model.unset()
无效,我不确定原因。
这是我目前使用Backbone的代码
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();
HTML和模板:
<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>
答案 0 :(得分:1)
您有一个简单的逻辑错误 - 您不应在检查中包含this.model.get(name) === ''
。
实际上,前面的if
表示您无法将Model的name
属性设置为空字符串。因此,除非您可以在应用程序的其他位置将其设置为空字符串,否则else if
条件永远不会。
这应该按照您的预期运作:
if (value !== '') {
this.model.set(name, value);
}
else if ( this.model.has(name)) {
this.model.unset(name);
}