Search code examples
javascriptmeteorreactive-programmingmeteor-helper

How Do I Make an Array of Objects a Reactive Data Source?


I have an array of objects. Say

var 
sidelist = [
    {
    name:"asdf", 
    id:1234,
    types:[...]


    }
];

Every object is turned into a box on the page using this construct

Template.global.side = function(){
    var obj = [], m;
    m = 1;
    for (var i in sides){
        obj.push({
            index : m,
            object : sides[i]
        });
    }

    return obj;
}

The HTML:

        {{#each side}}
            <div class="span{{this.index}}" id={{this.object.id}}>


                    <div class="side-head">{{this.object.name}}</div> 

</template>

There is a function that creates and pushes a new object into the array. How do I make the row of boxes reactively update on the page when the array they depend on changes?

So when I add a new object a new box should appear.


Solution

  • If you want to use Dependencies, it can look like this:

    var sidelist = ...;
    var sidelist_dep = new Deps.Dependency;
    

     

    Template.global.side = function(){
        sidelist_dep.depend();
        // Do your stuff here;
        return ...;
    };
    

     

    // Important: call this every time you change sidelist,
    // AFTER the change is made.
    sidelist_dep.changed();
    

     

    See: http://docs.meteor.com/#deps