I am trying out the Backbone.StickIt plugin for data-binding, my question is on initial render I display the Model defaults name and email. If I were to enter only my name in the contact form both name and email get rerendered, how can only set the inputs whos values have been entered? So if email value === '' don't be setting/rendering this?
Fiddle: http://jsfiddle.net/kyllle/e6z7gbta/
JS
var FormView = Backbone.View.extend({
template: _.template( $('.js-form-template').html() ),
events: {
'submit': 'onFormSubmit'
},
render: function() {
this.$el.html( this.template( this.model.toJSON() ) );
return this;
},
onFormSubmit: function(event) {
event.preventDefault();
var nameValue = this.$('input[id=name]').val(),
emailValue = this.$('input[id=email]').val();
this.model.set({
'name': nameValue,
'email': emailValue
});
}
});
var UserView = Backbone.View.extend({
bindings: {
'.js-name': 'name',
'.js-email': 'email'
},
template: _.template( $('.js-user-template').html() ),
render: function() {
this.$el.html( this.template( this.model.toJSON() ) );
this.stickit();
return this;
}
});
Template
<script type="text/template" class="js-user-template">
<h1>User Details</h1>
<p>Name: <span class="js-name"><%= name %></span></p>
<p>Email: <span class="js-email"><%= email %></span></p>
</script>
<script type="text/template" class="js-form-template">
<h1>Contact Form</h1>
<form action="/">
<fieldset>
<label for="name">Name</label>
<input type="text" id="name" class="form-text" />
</fieldset>
<fieldset>
<label for="email">Email</label>
<input type="email" id="email" class="form-text" />
</fieldset>
<fieldset class="form-actions">
<input type="submit" value="Submit" />
</fieldset>
</form>
</script>
If I understood correctly, you just need to add a simple validation before setting the values to the model, rather than blindly updating the model at once :