Javascript数组和Meteor会话 [英] Javascript arrays and Meteor session

查看:60
本文介绍了Javascript数组和Meteor会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我做了一个有趣的观察。尝试更新存储在Meteor会话存储中的阵列时,以下代码不会传播更改:

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);

但如果我改变第一行使用 Session.get(Tags ).slice(),取决于会话的所有内容都将相应更新。我想这是因为Meteor测试了一些相等的引用,因此不会更新任何内容。

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.

有没有更好的方法来管理存储的列表流星会话商店?

如果我现在尝试从集合中删除一个元素(使用 array.remove()此处)的code>,行为结果有点儿。 ...我在Meteor模板事件中执行此操作,代码如下所示:

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);
}

此输出:

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

所以不知何故, cardTags.indexOf(this); 语句似乎返回 -1 几乎适用于所有情况。我想我正在做一些从根本上说错误的事情,因为我现在对javascript,但不知何故我无法弄清楚这里发生了什么。

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.

为什么那些人对indexOf()的两次调用表现不同?

推荐答案

我认为这与 Backbone.js中的这种情况。为了触发更改事件,Meteor需要为数组提供新的引用,而不仅仅是旧数据的更新副本。

I believe this is the same as this situation in Backbone.js. In order for the change event to be triggered, Meteor needs to have a new reference for the array, not just an updated copy of the old one.

简而言之,在为了获得'正确'的行为,您需要克隆数组,进行所需的更改,然后执行Session.set('foo',myCopiedArray)。

In brief, in order to have the 'correct' behaviour, you'll need to clone the array, make the changes you want, and then do Session.set('foo', myCopiedArray).

这篇关于Javascript数组和Meteor会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆