How do I delete or remove Session variables?

前端 未结 3 1901
故里飘歌
故里飘歌 2020-12-14 00:37

Meteor has a Session that provides a global object on the client that you can use to store an arbitrary set of key-value pairs. Use it to store things like the currently sel

相关标签:
3条回答
  • 2020-12-14 00:53

    Session.set('name', undefined) or Session.set('name', null) should work.

    0 讨论(0)
  • 2020-12-14 01:05

    [note: this answer is for Meteor 0.6.6.2 through at least 1.1.0.2]

    [edit: updated to also explain how to do this while not breaking reactivity. Thanks to @DeanRadcliffe, @AdnanY, @TomWijsman, and @MikeGraf !]

    The data is stored inside Session.keys, which is simply an object, so you can manually delete keys:

    Session.set('foo', 'bar')
    delete Session.keys['foo']
    
    console.log(Session.get('foo')) // will be `undefined`
    

    To delete all the keys, you can simply assign an empty object to Session.keys:

    Session.set('foo', 'bar')
    Session.set('baz', 'ooka!')
    Session.keys = {}
    
    console.log(Session.get('foo')) // will be `undefined`
    console.log(Session.get('baz')) // will be `undefined`
    

    That's the simplest way. If you want to make sure that any reactive dependencies are processed correctly, make sure you also do something like what @dean-radcliffe suggests in the first comment. Use Session.set() to set keys to undefined first, then manually delete them. Like this:

    // Reset one value
    Session.set('foo', undefined)
    delete Session.keys.foo
    
    // Clear all keys
    Object.keys(Session.keys).forEach(function(key){ Session.set(key, undefined); })
    Session.keys = {}
    

    There will still be some remnants of the thing in Session.keyDeps.foo and Session.keyValueDeps.foo, but that shouldn't get in the way. 

    0 讨论(0)
  • 2020-12-14 01:07

    The disadvantage with using delete Session.keys['foo'] is that your template will not hot reload if the session key holds an array. For instance, if you are doing

    Template.mytempl.helpers({
        categories: function() {
            return Session.get('srch-categories')
        }
    })
    

    and in your template

    {{#if categories}}
        {{#each categories}}
            {{this}}
        {{/each}}
    {{/if}}
    

    And categories is an array, if you delete the session key, your template will continue to display the last value of categories.

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