Javascript arrays and Meteor session

后端 未结 2 1965
慢半拍i
慢半拍i 2021-02-20 08:57

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:



        
相关标签:
2条回答
  • 2021-02-20 09:07

    In short: Use var index = cardTags.indexOf(this.toString()); instead.

    Long version:

    When using strings in JavaScript, those are strings, whereas typeof 'test' returns string.

    Let's take a look at the following code in order to get find out another way to represent strings in JavaScript:

    var func = function () {
        return this;
    };
    console.log(func.call('test'));
    

    The console (at least FireBug) won't show us "test", but instead it shows String {0="t", 1="e", 2="s", 3="t" }. typeof would return "object".

    The content of the this statement seems to need to be an object. In order to convert a string into a "String" object we can do console.log(new String('test'));, which is the same as the previously logged value.

    To convert a string object into a string (data type), just use its prototype toString.

    0 讨论(0)
  • 2021-02-20 09:21

    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.

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

    0 讨论(0)
提交回复
热议问题