Javascript arrays and Meteor session

Viewed 6110

I have made an interesting observation. When trying to update an array that is stored in the Meteor session storage, the following code will not propagate the changes:

var tags = Session.get("Tags");
tags.push("a");
Session.set("Tags", tags);

But if I change the first line to use Session.get("Tags").slice(), everything depending on the session will update accordingly. I guess this is due to the fact that Meteor tests some references for equality and therefore does not update anything.

Is there a better way to manage lists stored in the meteor session store?

If I now try to remove an element from the collection (using array.remove() from here), the behavior turns out to be a bit ... of ... I am doing this inside a Meteor template event, the code looks like this:

"click .taglist li" : function(e) {
  var tags = Session.get("Tags").slice();
  var index = cardTags.indexOf(this);

  Meteor._debug(Session.get("Tags").slice().indexOf("a"));
  Meteor._debug("Removing tag \"" + this + "\", index: " + index, ", typeof(this) = " + typeof(this).toString());

  tags.remove(index);
  Session.set("Tags", tags);
}

This outputs:

1
Removing tag "a", index: -1, typeof(this) = string

So somehow, the cardTags.indexOf(this); statement seems to return -1 for almost any case. I guess I am doing something fundamentally wrong, as I am quite now to javascript, but somehow I can not figure out whats going on here.

Why will those two calls to indexOf() behave different?

2 Answers
Related