2015-08-21 113 views
2

我想將變量從服務器端傳遞到客戶端的模板。 在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

回答

2

看起來像一個奇怪的結構給我。你不希望幫助者生成私鑰,我不這麼認爲。每次模板呈現時,它都會生成一個密鑰並將其打印出來。但是,無論如何,您不能像這樣調用方法,因爲在客戶端上使用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.'); 
    } 
    } 
    }); 
} 
1

一般使用流星「法」將是要走的路:

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