How to retain list item select state after collection update?


#1

I am setting custom style for selected item in a list using click handlers - but loosing that style when the collection updates - what is the right way to do this?

Template['esXYZTable'].events({
    'click li': function (e, template) {
        $(e.currentTarget).addClass("esxyzSelected");
    }
});

As seen above a new classs is added to the selected li to make it appear different on UI. But it looses that class after collection update.

The html

<ul>			
	{{#each xyzOptions}}
	<li>
	   {{this.xField}} - {{this.yField}}
	</li>
	{{/each}}
</ul>

the collection is updated as something like below

       self.esxyzOptions.remove({});//clear old data
        for (var i = 0; i < timeFields.length; ++i)        {
            for (var j = 0; j < measureFields.length; ++j)            {
                trendObj['yField'] = measureFields[j];
                trendObj['_id'] = measureFields[j];;
                self.esxyzOptions.insert(trendObj);
            }
        }

Q: Based on the currently selected list Item, I am showing a form - now, how to make my list item retain the selection (so that the form can continue to be displayed) even after the collection update?

Right now, after collection update, user has to manually click on that old item again to select it and get that associated form displayed.


#2

You might want to use something like a Session variable to store which item is selected and than use a helper function to pass that Session variable to your template. I believe the issue is you’re using jQuery to manipulate the DOM outside of the reactive template so that’s getting overridden when the template is rerun after the collection change.


#3

Thank you.

Since the list is too huge, did not go for reactive classes to take care of the selection. For example, I could have done something like this:

<li class= {{if is selected}} clsSelected {{/if}}> ...

and then have a helper is Selected method that returns true only for the selected item (based on, say, some session variable or template instance variable that keeps track of the selected item’s id).

But unforutnately that would be too slow (since that is selected method would have to run for all items in the list every time there is click / selection change.

What is the Meteor’s recommended way?

Manually keep adjusting the DOM CSS after every collection update non-re-actively or some other nice reactive techniques exists that would not need evaluating the condition for all items?