Reputation: 4400
I am not sure why the model.unset()
event is not firing.
I am setting a model's view based on input blur events. When an input has a value the model is set with the value. If that value is than removed from the form I want to delete the property from the model but my model.unset()
is not working and I am not sure why.
Here is my current code using 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 and templates:
<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>
Upvotes: 0
Views: 283
Reputation: 30330
You have a simple logic error - you should not include this.model.get(name) === ''
in your check.
In fact, the preceding if
means that you cannot set the Model's name
attribute to an empty String. Therefore, unless you could set it to an empty String elsewhere in your application, the else if
condition can never be met.
This should work as you expect:
if (value !== '') {
this.model.set(name, value);
}
else if ( this.model.has(name)) {
this.model.unset(name);
}
Upvotes: 1