在我的客户端,我显示了一个用户列表和一个小图表,用于存储在数据库中的每个用户的点数(使用称为迷你图的 jQuery 插件)。
绘制图表是在Template.rendered方法上完成的
// client/main.js
Template.listItem.rendered = function() {
var arr = this.data.userPoints // user points is an array of integers
$(this.find(".chart")).sparkline(arr);
}
现在我在服务器端有一个 Meteor 方法,它会定期调用以更新用户点数。
Meteor.methods({
"getUserPoints" : function getUserPoints(id) {
// access some API and fetch the latest user points
}
});
现在我希望在调用 Meteor 方法时自动更新图表。我在模板上有一个方法可以调用这个 Meteor 方法。
Template.listItem.events({
"click a.fetchData": function(e) {
e.preventDefault();
Meteor.call("getUserPoints", this._id);
}
});
如何将这段代码变成“响应式(Reactive)”代码?
最佳答案
您需要将响应式(Reactive)数据源
(Session,ReactiveVar)与Tracker一起使用.
使用 ReactiveVar:
if (Meteor.isClient) {
Template.listItem.events({
"click a.fetchData": function(e) {
e.preventDefault();
var instance = Template.instance();
Meteor.call("getUserPoints", this._id, function(error, result) {
instance.userPoints.set(result)
});
}
});
Template.listItem.created = function() {
this.userPoints = new ReactiveVar([]);
};
Template.listItem.rendered = function() {
var self = this;
Tracker.autorun(function() {
var arr = self.userPoints.get();
$(self.find(".chart")).sparkline(arr);
})
}
}
使用 session :
if (Meteor.isClient) {
Template.listItem.events({
"click a.fetchData": function(e) {
e.preventDefault();
Meteor.call("getUserPoints", this._id, function(error, result) {
Session.set("userPoints", result);
});
}
});
Template.listItem.rendered = function() {
var self = this;
Tracker.autorun(function() {
var arr = Session.get("userPoints");
$(self.find(".chart")).sparkline(arr);
})
}
}
这些实现之间的区别:
A ReactiveVar is similar to a Session variable, with a few differences:
ReactiveVars don't have global names, like the "foo" in Session.get("foo"). Instead, they may be created and used locally, for example attached to a template instance, as in: this.foo.get().
ReactiveVars are not automatically migrated across hot code pushes, whereas Session state is.
ReactiveVars can hold any value, while Session variables are limited to JSON or EJSON.
Deps 已弃用,但仍可使用。
关于javascript - Meteor - 我如何使用 Deps 制作这个 "reactive"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25722933/