TAGS :Viewed: 2 - Published at: a few seconds ago

[ Using Marionette and LoDash to populate input value ]

My goal is to populate my Marionette template when the model changes.

I have a template that is a form:

<!-- EditContact.html -->
    <label for="name">Name</label>
    <input type="text" id="name" name="name" maxLength="64" value="{{name}}">

    <label for="email">Email</label>
    <input type="text" id="email" name="email" value="{{email}}" />

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

    success: function(){
        contactInfo = myContactInfo.models[0];
        that.editContactLayout.model = 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?

Answer 1

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();

            // 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});



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.