主干模型.未设置不删除属性
Backbone model.unset not removing property
我不确定为什么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);
}
相关文章:
- 在不知道深度或父属性的情况下从对象中删除属性
- 如何从对象中删除属性
- 使用jQuery添加和删除属性
- 为什么没有从数组中存在的对象中删除属性
- 删除属性后刷新DOM,而不象chrome那样刷新页面
- Jquery 在当前之前从元素中删除属性
- 在窗口调整大小时删除属性
- 如何从使用 jquery 添加的项中删除属性
- 从 JavaScript 中的 XAML 元素中删除属性
- 主干模型.未设置不删除属性
- 无法在单击时添加/删除属性
- 从主干.js模型中删除属性
- 如果选中复选框,请删除属性
- jQuery单击功能可从元素中删除属性并在单独单击时恢复属性
- 如果找到特定类,如何添加和删除属性
- 如何使用 Javascript 从 DOM 元素中删除属性
- 从 Javascript 对象中删除属性
- 量角器未知错误,从 DOM 中删除属性
- 如何使用jquery onchange事件在HTML中添加和删除属性
- 如何从任何级别的嵌套javascript对象中删除属性