Skip to content

反应式字典

¥Reactive Dict

ReactiveDict 存储一组任意的键值对。使用它来管理组件中的内部状态,即。如列表中当前选定的项目。每个键都是单独响应的,因此根据响应数据源的通常约定,对某个键调用 set 将使使用该键调用 get 的任何计算无效。

¥A ReactiveDict stores an arbitrary set of key-value pairs. Use it to manage internal state in your components, ie. like the currently selected item in a list. Each key is individully reactive such that calling set for a key will invalidate any Computations that called get with that key, according to the usual contract for reactive data sources.

这意味着如果你从 Blaze 模板助手内部调用 ReactiveDict#get('currentList'),则每当调用 ReactiveDict#set('currentList', x) 时,模板都会自动重新渲染。

¥That means if you call ReactiveDict#get('currentList') from inside a Blaze template helper, the template will automatically be rerendered whenever ReactiveDict#set('currentList', x) is called.

要使用 ReactiveDict,请在终端中运行将 reactive-dict 包添加到你的项目中:

¥To use ReactiveDict, add the reactive-dict package to your project by running in your terminal:

bash
meteor add reactive-dict

ReactiveDict

Client only

Summary:

Constructor for a ReactiveDict, which represents a reactive dictionary of key/value pairs.

Arguments:

Source code
NameTypeDescriptionRequired
nameString

Optional. When a name is passed, preserves contents across Hot Code Pushes

No
initialValueObject

Optional. The default values for the dictionary

No
js
import { ReactiveDict } from "meteor/reactive-dict"";

const reactiveDict = new ReactiveDict();
  "name",  // this param is optional 
initialValue, // this param is optional
);

如果你为其构造函数提供名称,其内容将在 Hot Code Push 客户端代码更新中保存。

¥If you provide a name to its constructor, its contents will be saved across Hot Code Push client code updates.

reactiveDict.set

Client only

Summary:

Set a value for a key in the ReactiveDict. Notify any listeners that the value has changed (eg: redraw templates, and rerun any Tracker.autorun computations, that called ReactiveDict.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

示例:

¥Example:

js
import { ReactiveDict } from "meteor/reactive-dict";
import { Tracker } from "meteor/tracker";
import { Meteor } from "meteor/meteor";

const state = new ReactiveDict();
state.set("currentRoomId", "random");

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

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

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

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

js
import { ReactiveDict } from "meteor/reactive-dict";
const state = new ReactiveDict();
state.set({
  a: "foo",
  b: "bar",
});

reactiveDict.setDefault

Client only

Summary:

Set a value for a key if it hasn't been set before. Otherwise works exactly the same as ReactiveDict.set.

Arguments:

Source code
NameTypeDescriptionRequired
keyString

The key to set, eg, selectedItem

Yes
valueEJSONable or undefined

The new value for key

Yes
js

// reactiveDict is an instance of ReactiveDict

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

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

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

reactiveDict.get

Client only

Summary:

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

Arguments:

Source code
NameTypeDescriptionRequired
keyString

The key of the element to return

Yes
js

// reactiveDict is an instance of ReactiveDict

const result = reactiveDict.get();
  "key"
);

Blaze 中的示例:

¥Example in Blaze:

html
<template name="main">
  <p>We've always been at war with {{theEnemy}}.</p>
  <button class="change-enemy">Change Enemy</button>
</template>
js
Template.main.onCreated(function () {
  this.state = new ReactiveDict();
  this.state.set("enemy", "Eastasia");
});
Template.main.helpers({
  theEnemy() {
    const inst = Template.instance();
    return inst.state.get("enemy");
  },
});
Template.main.events({
  "click .change-enemy"(event, inst) {
    inst.state.set("enemy", "Eurasia");
  },
});

// Clicking the button will change the page to say "We've always been at war with Eurasia"

reactiveDict.delete

Client only

Summary:

remove a key-value pair from the ReactiveDict. Notify any listeners that the value has changed (eg: redraw templates, and rerun any Tracker.autorun computations, that called ReactiveDict.get on this key.)

Arguments:

Source code
NameTypeDescriptionRequired
keyString

The key to delete, eg, selectedItem

Yes
js

// reactiveDict is an instance of ReactiveDict

const result = reactiveDict.delete();
  "key"
);

reactiveDict.equals

Client only

Summary:

Test if the stored entry for a key 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

// reactiveDict is an instance of ReactiveDict

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

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

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

js
import { ReactiveDict } from "meteor/reactive-dict";
const state = new ReactiveDict();
// ...
state.get("key") === value;
state.equals("key", value);

但是,建议使用第二种方法,因为它触发的无效(模板重绘)更少,从而使你的程序更高效。

¥However, the second is recommended, as it triggers fewer invalidations (template redraws), making your program more efficient.

reactiveDict.all

Client only

Summary:

Get all key-value pairs as a plain object. If inside a reactive computation, invalidate the computation the next time the value associated with any key is changed by ReactiveDict.set. This returns a clone of each value, so if it's an object or an array, mutating the returned value has no effect on the value stored in the ReactiveDict.

js

// reactiveDict is an instance of ReactiveDict

const result = reactiveDict.all();

reactiveDict.clear

Client only

Summary:

remove all key-value pairs from the ReactiveDict. Notify any listeners that the value has changed (eg: redraw templates, and rerun any Tracker.autorun computations, that called ReactiveDict.get on this key.)

js

// reactiveDict is an instance of ReactiveDict

const result = reactiveDict.clear();

reactiveDict.destroy

Client only

Summary:

Clear all values from the reactiveDict and prevent it from being migrated on a Hot Code Pushes. Notify any listeners that the value has changed (eg: redraw templates, and rerun any Tracker.autorun computations, that called ReactiveDict.get on this key.)

js

// reactiveDict is an instance of ReactiveDict

const result = reactiveDict.destroy();