如何访问 Iron Router 中的数据?
How to reach data within Iron Router?
在我的页面上,有 url object/:_id
,用户通常应该只访问一个文档,我是这样设置的:
waitOn: function() {
return Meteor.subscribe('objects', this.params._id),
},
data: function() {
return Objects.findOne({_id: this.params._id})
}
但是,也应该可以查看和处理其他一些对象,但只能是那些与我们正在查看的对象颜色相同的对象,所以我也需要让那些可以访问。
这是我认为可行的方法:
onBeforeAction: function() {
var self = Objects.findOne({_id: this.params._id})
var color = self.color
Session.set('chosenColor', color)
this.next()
},
waitOn: function() {
return Meteor.subscribe('objects', Session.get('chosenColor'))
},
data: function() {
return Objects.findOne({_id: this.params._id})
}
应该注意的是,这起初有效,但突然莫名其妙地停止了。 self
由于某种原因现在总是 "undefined"。
在 Iron Router 中访问此数据的正确方法是什么?
尝试在数据中使用 this.ready()
条件:
waitOn: function() {
return Meteor.subscribe('objects');
},
data: function() {
if (this.ready()) {
var self = Objects.findOne({_id: this.params._id});
var color = self.color;
return Objects.findOne({_id: this.params._id}, color);
}
}
这里有循环逻辑:在订阅将要发布该对象的集合之前您试图加载一个对象并获取其颜色。只需将颜色逻辑移至服务器上的发布功能即可。
客户端 js:
waitOn: function() {
return Meteor.subscribe('objects', this.params._id);
},
data: function() {
return Objects.findOne({_id: this.params._id})
}
服务器 js:
Meteor.publish('objects',function(id){
check(id, Meteor.Collection.ObjectID);
var self = Objects.findOne({_id: id})
if ( self ){
var color = self.color;
return Objects.find({ color: color });
}
else this.ready();
});
在我的页面上,有 url object/:_id
,用户通常应该只访问一个文档,我是这样设置的:
waitOn: function() {
return Meteor.subscribe('objects', this.params._id),
},
data: function() {
return Objects.findOne({_id: this.params._id})
}
但是,也应该可以查看和处理其他一些对象,但只能是那些与我们正在查看的对象颜色相同的对象,所以我也需要让那些可以访问。
这是我认为可行的方法:
onBeforeAction: function() {
var self = Objects.findOne({_id: this.params._id})
var color = self.color
Session.set('chosenColor', color)
this.next()
},
waitOn: function() {
return Meteor.subscribe('objects', Session.get('chosenColor'))
},
data: function() {
return Objects.findOne({_id: this.params._id})
}
应该注意的是,这起初有效,但突然莫名其妙地停止了。 self
由于某种原因现在总是 "undefined"。
在 Iron Router 中访问此数据的正确方法是什么?
尝试在数据中使用 this.ready()
条件:
waitOn: function() {
return Meteor.subscribe('objects');
},
data: function() {
if (this.ready()) {
var self = Objects.findOne({_id: this.params._id});
var color = self.color;
return Objects.findOne({_id: this.params._id}, color);
}
}
这里有循环逻辑:在订阅将要发布该对象的集合之前您试图加载一个对象并获取其颜色。只需将颜色逻辑移至服务器上的发布功能即可。
客户端 js:
waitOn: function() {
return Meteor.subscribe('objects', this.params._id);
},
data: function() {
return Objects.findOne({_id: this.params._id})
}
服务器 js:
Meteor.publish('objects',function(id){
check(id, Meteor.Collection.ObjectID);
var self = Objects.findOne({_id: id})
if ( self ){
var color = self.color;
return Objects.find({ color: color });
}
else this.ready();
});