Я пробую плагин Backbone.StickIt для data-binding
, мой вопрос касается начального рендеринга, который я отображаю Модель по умолчанию name
и email
. Если бы я должен был ввести только свое имя в контактную форму, и имя, и адрес электронной почты будут перерисованы, как можно установить только те входные данные, чьи значения были введены? Итак, если значение электронной почты === '' не нужно устанавливать/рендерить это?
Скрипт: 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;
}
});
Шаблон
<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>