BB: Simple View
by kyllle
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0-alpha1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/backbone.js/1.2.2/backbone-min.js"></script>
<script type="text/template" class="js-clearing-contact">
<div class="input-field">
<label class="input-field__label" for="name">Name</label>
<input class="input-field__input js-input-field" type="text" name="name">
</div>
<div class="input-field">
<label class="input-field__label" for="phone">Telephone Number</label>
<input class="input-field__input js-input-field" type="text" name="phone">
</div>
<div class="input-field">
<label class="input-field__label" for="email">Email Address</label>
<input class="input-field__input js-input-field" type="email" name="email">
</div>
<button class="js-add-contact">Add Contact</button>
</script>
<script type="text/template" class="js-clearing-contact--success">
<h1>Contact details successfully submitted</h1>
</script>
JavaScript
console.clear();
var ContactModel = Backbone.Model.extend();
var ContactView = Backbone.View.extend({
className: 'contact-screen',
template: _.template( $('.js-clearing-contact').html() ),
templateSuccess: _.template( $('.js-clearing-contact--success').html() ),
events: {
'click .js-add-contact': 'onAddContact'
},
initialize: function () {
console.log('init', this.$el);
this.model.on('change:contacts', this.onModelSet, this);
},
render: function () {
this.$el.html(this.template(this.model.toJSON()));
return this;
},
// Step 1: On Submit grab each of the form values, and make our push object
onAddContact: function() {
// Loop through inputs
var inputs = this.$el.find('.js-input-field'),
newContact = {},
contacts = _.clone(this.model.get('contacts')); // http://stackoverflow.com/questions/8491546/models-change-event-wont-fire-when-updating-an-array
console.log(contacts);
inputs.each(function(index, element) {
// needs an id also clearingFirmId
return newContact[element.name] = element.value;
});
contacts.push(newContact);
console.log(contacts);
this.model.set({
contacts: contacts
});
},
onModelSet: function() {
console.log('Model Set', JSON.stringify(this.model.get('contacts'), null, 4));
_.each(this.model.contacts, function(contact) {
console.log(contact);
});
this.$el.empty().html( this.templateSuccess() );
// Do whatever...
},
dispose: function() {
console.log('Dispose called');
this.remove();
}
});
var contactModel = new ContactModel();
contactModel.set({
"id": 1,
"name": "Joe Bloggs",
"contacts": [{
...