Skip to content

会话

¥Session

Meteor 客户端会话 API 的文档。

¥Documentation of Meteor's client-side session API.

Session 在客户端上提供了一个全局对象,你可以使用它来存储任意一组键值对。使用它来存储列表中当前选定的项目等内容。

¥Session 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 selected item in a list.

Session 的特殊之处在于它是反应式的。如果你从模板内部调用 Session.get('currentList'),则每当调用 Session.set('currentList', x) 时,模板都会自动重新渲染。

¥What's special about Session is that it's reactive. If you call Session.get('currentList') from inside a template, the template will automatically be rerendered whenever Session.set('currentList', x) is called.

要将 Session 添加到你的应用,请在你的终端中运行此命令:

¥To add Session to your application, run this command in your terminal:

bash
meteor add session

Session.set

Client only

Summary:

Set a variable in the session. Notify any listeners that the value has changed (eg: redraw templates, and rerun any Tracker.autorun computations, that called Session.get on this key.)

Arguments:

Source code
NameTypeDescriptionRequired
keyString

The key to set, eg, selectedItem

Yes
valueEJSONable or undefined

The new value for key

Yes
js
import { Session } from 'meteor/session';
import { Tracker } from 'meteor/tracker';
import { Meteor } from 'meteor/meteor';

Tracker.autorun(() => {
  Meteor.subscribe('chatHistory', { room: Session.get('currentRoomId') });
});

// Causes the function passed to `Tracker.autorun` to be rerun, so that the
// 'chatHistory' subscription is moved to the room 'home'.
Session.set('currentRoomId', 'home');

Session.set 也可以使用键和值的对象来调用,这相当于在每个键/值对上单独调用 Session.set

¥Session.set can also be called with an object of keys and values, which is equivalent to calling Session.set individually on each key/value pair.

js
Session.set({
  a: 'foo',
  b: 'bar'
});

Session.setDefault

Client only

Summary:

Set a variable in the session if it hasn't been set before. Otherwise works exactly the same as Session.set.

Arguments:

Source code
NameTypeDescriptionRequired
keyString

The key to set, eg, selectedItem

Yes
valueEJSONable or undefined

The new value for key

Yes
js
import { Session } from "meteor/session";


const result = Session.setDefault();
  "key",
{ num: 42 , someProp: "foo" },
);

这在初始化代码中很有用,可以避免每次加载新版本的应用时都重新初始化会话变量。

¥This is useful in initialization code, to avoid re-initializing a session variable every time a new version of your app is loaded.

Session.get

Client only

Summary:

Get the value of a session variable. If inside a reactive computation, invalidate the computation the next time the value of the variable is changed by Session.set. This returns a clone of the session value, so if it's an object or an array, mutating the returned value has no effect on the value stored in the session.

Arguments:

Source code
NameTypeDescriptionRequired
keyString

The name of the session variable to return

Yes

Blaze.js 中的此示例

¥This example in Blaze.js

html
<template name="main">
  <p>We've always been at war with {{theEnemy}}.</p>
</template>
js
Template.main.helpers({
  theEnemy() {
    return Session.get('enemy');
  }
});

Session.set('enemy', 'Eastasia');
// Page will say "We've always been at war with Eastasia"

Session.set('enemy', 'Eurasia');
// Page will change to say "We've always been at war with Eurasia"

Session.equals

Client only

Summary:

Test if a session variable is equal to a value. If inside a reactive computation, invalidate the computation the next time the variable changes to or from the value.

Arguments:

Source code
NameTypeDescriptionRequired
keyString

The name of the session variable to test

Yes
valueString, Number, Boolean, null or undefined

The value to test against

Yes
js
import { Session } from "meteor/session";


const result = Session.equals();
  "key",
"value",
);

如果值是标量,则这两个表达式执行相同的操作:

¥If value is a scalar, then these two expressions do the same thing:

js
Session.get('key') === value
Session.equals('key', value)

...但第二个总是更好。它会触发更少的无效(模板重绘),从而使你的程序更高效。

¥...but the second one is always better. It triggers fewer invalidations (template redraws), making your program more efficient.

Blaze.js 中的此示例:

¥This example in Blaze.js:

html

<template name="postsView">
  {{#each posts}}
    {{> postItem}}
  {{/each}}
</template>

<template name="postItem">
  <div class="{{postClass}}">{{title}}</div>
</template>
js

Template.postsView.helpers({
  posts() {
    return Posts.find();
  }
});

Template.postItem.helpers({
  postClass() {
    return Session.equals('selectedPost', this._id)
      ? 'selected'
      : '';
  }
});

Template.postItem.events({
  'click'() {
    Session.set('selectedPost', this._id);
  }
});

此处使用 Session.equals 意味着当用户单击某个项目并更改选择时,只会重新渲染新选择的项目和新取消选择的项目。

¥Using Session.equals here means that when the user clicks on an item and changes the selection, only the newly selected and the newly unselected items are re-rendered.

如果使用了 Session.get 而不是 Session.equals,那么当选择发生变化时,所有项目都会重新渲染。

¥If Session.get had been used instead of Session.equals, then when the selection changed, all the items would be re-rendered.

对于对象和数组会话值,你不能使用 Session.equals;相反,你需要使用 underscore 软件包并写入 _.isEqual(Session.get(key), value)

¥For object and array session values, you cannot use Session.equals; instead, you need to use the underscore package and write _.isEqual(Session.get(key), value).