流星:将变量从服务器传递到客户端

问题描述:

我想将变量从服务器端传递到客户端的模板。 在main.html中,我有这样的模板:流星:将变量从服务器传递到客户端

<template name="hello"> 
    ... 
    <p>{{privateKey}}</p> 
</template> 

在main.js,我想是这样的:

if (Meteor.isClient) { 
    Template.hello.helpers({ 
     privateKey : function() { 
      return 'call to function makePrivateKey'; 
     } 
    }); 
} 

if (Meteor.isServer) { 
    Meteor.methods({ 
     makePrivateKey: function() { 
      var privKey = bitcoinjs.ECKey.makeRandom(); 
      return privKey.toWIF(); 
     } 
    }); 
} 

如何从服务器端和打印 私人invoque功能makePrivateKey键入我的模板? 我不想使用会话变量或动态变量。

+0

为什么你不希望使用会话变量或ReactiveVars? – Curtis

+0

我可能会为每个页面有很多变量,并且它们不会随着时间而改变,所以实际上,对于html页面,它们将是常量。 – jfjobidon

看起来像一个奇怪的结构给我。你不希望帮助者生成私钥,我不这么认为。每次模板呈现时,它都会生成一个密钥并将其打印出来。但是,无论如何,您不能像这样调用方法,因为在客户端上使用Meteor.call需要回调,所以再次,这不是这样做的方法。然而,这可能是工作:

if (Meteor.isClient) { 
    Template.hello.events({ 
    'click .generate-key': function() { 
     Meteor.call('makePrivateKey', function (error, result) { 
     if (!error) { 
      Session.set('credentials/privKey', result.privKey); 
     } 
     else { 
      // handle error 
     } 
     }) 
    } 
    }); 

    Template.hello.helpers({ 
    privateKey: function() { 
     return Session.get('credentials/privKey'); 
    } 
    }); 
} 

if (Meteor.isServer) { 
    Meteor.methods({ 
    makePrivateKey: function() { 
    try { 
     var privKey = bitcoinjs.ECKey.makeRandom(); 
     return {privKey: privKey.toWIF()}; 
    } catch (e) { 
     throw Meteor.Error('some-error', 'Bad things happened.'); 
    } 
    } 
    }); 
} 

一般使用流星“法”将是要走的路:

if (Meteor.isClient) { 
    Template.hello.helpers({ 
    privateKey : function() { 
     return Meteor.call(makePrivateKey); 
    } 
    }); 
}