【问题标题】:Accessing meteor Template.instance().data from method call callback从方法调用回调访问流星 Template.instance().data
【发布时间】:2016-03-31 06:01:47
【问题描述】:

我在流星模板管理器中有这样一段代码:

"click #refuse": function() {
Meteor.call("removeUserFromEvent", this._id, Meteor.userId());
if (Template.instance().data.participants.length === Template.instance().data.orderedParticipants.length) {
  Meteor.call("updateEventStatus", this._id, "ordered");
}
Router.go("/");

}

我想让if(...){...} 的东西在Meteor.call(...) 回调中执行,比如

"click #refuse": function() {
Meteor.call("removeUserFromEvent", this._id, Meteor.userId(), function(){
  if (Template.instance().data.participants.length === Template.instance().data.orderedParticipants.length) {
  Meteor.call("updateEventStatus", this._id, "ordered");
}
});
Router.go("/");
}

但如果我尝试这样做,结果是在该回调内部 Template.instance() 返回 null 并且我无法从模板中获取数据。

我怎样才能在方法回调中放置这些东西(我的意思是,获取一些当前状态参数并取决于这些调用或不调用另一个方法)?也许 Template.instance().data 是存储状态参数的错误位置? Template.instance.data 是响应式的吗?或许我应该以某种方式更改架构,以使此类功能能够驻留在回调中?

【问题讨论】:

    标签: javascript meteor


    【解决方案1】:

    这是一个事件处理程序,事件处理程序函数接受事件和模板作为参数,如'event target': function(event, template) {},因此您的代码可以修改为:

    "click #refuse": function(evt,tmp) {
      // get and cache your template data context references;
      var participants = tmp.data.participants;
      var orderedParticipants = tmp.data.orderedParticipants;
    
      // this._id is not reliable, you should use Blaze.getData() on the event target
      var _id = Blaze.getData(event.currentTarget)._id;
    
      var userId = Meteor.userId();
    
      // make sure your callback function accepts error and result 
      Meteor.call("removeUserFromEvent", _id, userId, function(err,res) {
    
        if (err) {/* handle error */}
    
        if (res) {
    
          if (participants.length === orderedParticipants.length) {
    
            Meteor.call("updateEventStatus", _id, "ordered", function(err,res) {
    
              if (err) {/* handle error */}
    
              if (res) {
                // perhaps you would like to redirect to home after successful operation only
                Router.go("/");
              }
    
            });
          }
    
        }
    
      });
    
    }
    

    PS:这里的回调太多了,所以你可能想看看 Promise 来简化这段代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-03-12
      • 1970-01-01
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多