Search code examples
javascripteventsbackbone.jsmarionette

how to update the view based on a object change in backbone and marionette?


i have a view:

define(['backbone', 'hbs!tmpl/test_tmpl'],
function (Backbone, TestTmpl) {
    'use strict';
    return Backbone.Marionette.ItemView.extend({
        initialize: function () {
            this.projects = {};
        },
        template: TestTmpl,
        templateHelpers: function () {
            return {
                projects: this.projects
            }
        },
        ui: {},
        events: {},
        onRender: function () {
            this.projects = {title: 'a'};
            return this;
        }
    });
});

then in the view:

{{#each projects}}{{this.title}}{{/each}}

in the onRender() method i update the project this.projects = {title: 'a'}; and when that is set, i want the view data to update as well

any ideas?


Solution

  • Try to call

    this.render(); 
    

    Typically, you would use a collectionview instead of an itemview.
    If you happen to need more HTML surrounding the wrapping element, use a compositeview instead.

    Note that a collectionview takes a Backbone Collection when you pass it:

    var collectionview = new CollectionView({ collection: bbCollection }); 
    

    An itemview takes a model:

    var itemview = new ItemView({ model: bbModel}); 
    

    For your example, using a collectionview removes the need to create a loop within the template.
    You can access the current itemview's properties by calling

    this.model.get("property"); 
    

    On the itemview.

    In your example, it would appear to me that you rather have an array instead of an object:

    var projects = [{ title: "X"}, { title: "Y" }]; 
    

    You can create a Backbone collection on the fly this way:

    var projects_collection = new Backbone.Collection(projects); 
    

    And pass it on to the collectionview:

    //First create a Marionette Collectionview, then: 
    var projectsCollview = new ProjectsCollview({ collection: projects_collection });