My goal is to populate my Marionette template when the model changes.
I have a template that is a form:
<!-- EditContact.html -->
<fieldset>
<label for="name">Name</label>
<input type="text" id="name" name="name" maxLength="64" value="{{name}}">
</fieldset>
<fieldset>
<label for="email">Email</label>
<input type="text" id="email" name="email" value="{{email}}" />
</fieldset>
In my Controller.js, I fetching the model:
//this is a Backbone Collection
myContactInfo = new ContactInfo({
url: this.getInfoUri+'?cId=X342;3&transfer=0',
cId: cId
});
myContactInfo.fetch({
success: function(){
contactInfo = myContactInfo.models[0];
that.editContactLayout.model = contactInfo;
console.log(contactInfo);
}
});
I use the same layout for creating records. How do I update the view to automatically populate the fields with the model. Do I have to manually use jquery for each element or can I do it in the view using lodash?
Looks like you're looking for an edit contact action exemple. Following as an example that should work fine.
var ContactController = Backbone.Marionette.Controller.extend({
editAction: function(contactId) {
ContactCollection = Backbone.Collection.extend({
url: "/contacts"
});
var contactCollection = new ContactCollection();
contactCollection.fetch().done(function(){
// executed after the contacts from server are retrieved
// get the specific contactId
var contact = contactCollection.get(contactId);
// show model in the edit view
var editView = new ContactEditView({model: contact});
applayout.show(editView);
});
}
});
Marionette views have a property "modelEvents" e "collectionEvents". Those should be used as much as possible as they make your code cleaner.
Check out the docs about them: http://marionettejs.com/docs/marionette.itemview.html#modelevents-and-collectionevents.