سؤال

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.

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

In almost all cases, you should put the objects in a Meteor Collection instead of an array that is part of a reactive object. There are many reasons for this, including the following

  • Adding, removing, searching, and updating will all be faster
  • The reactivity will be on the element level instead of the array
  • Meteor won't re-render the whole set of objects when something is added or deleted - just the change
  • You can define a sort order on the collection, making it much more flexible than a fixed sequence

Take a look at Andrew Wilcox's isolate-value smart package: https://atmosphere.meteor.com/package/isolate-value

The README contains the exact example of selectively rerendering relevant templates when values are added/removed from an array stored in a Session varaible.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top