不会设置Meteor调用范围变量

时间:2016-07-17 22:02:36

标签: meteor

我在Meteor.call程序的范围上遇到了很多麻烦。它不会将我的范围变量设置为result.length

'takeaways': function (userId) {
    var len = 0;

    Meteor.call('userTakeaways', userId, function (error, result) {
        if (error) {
            console.log('there was an error finding the number of messages that were takeaways')
        } else {
            len = result.length; // result.length is 2
        }
    });

    console.log(len); // still 0

    return len;
}

请帮忙!

谢谢:)

2 个答案:

答案 0 :(得分:1)

len不是反应变量。因此,如果len值发生变化,则不会更新空格键值。

所以这里有两种解决这个问题的方法: 1.使用反应性var / session。

 //Make sure you have install reactive var package  
    var len = new ReactiveVar(0); 
    Template['name'].helpers({ 
        'takeaways': function (userId) {
            Meteor.call('userTakeaways', userId, function (error, result) {
               if (error) {
                   console.log('there was an error finding the number of messages that were takeaways')
               } else {
                  len.set(result.length); // result.length is 2
               }
           }); 
        console.log(len.get()); // You will get 2 when response come from you method call. 
        return len.get(); 
        } 
     });

2。使用' simple:reactive-method'封装

 takeaways : function(userId){
      return ReactiveMethod.call('userTakeaways', userId).length;
  }

答案 1 :(得分:0)

尝试添加else语句

  

return len = result.length;

正如你可以看到的那样。

'takeaways': function (userId) {
    var len = 0;

    Meteor.call('userTakeaways', userId, function (error, result) {
        if (error) {
            console.log('there was an error finding the number of messages that were takeaways')
        } else {
            return len = result.length; // result.length is 2
        }
    });

console.log(len); // still 0

return len;

}