2012-05-20 56 views
41

我試過to understand this post regarding this concept,但是,我沒有得到它。我有以下簡單的設置:如何讓Meteor.Call返回模板的值?

/server/test.js 
Meteor.methods({ 
    abc: function() { 
    var result = {}; 
    result.foo = "Hello "; 
    result.bar = "World!"; 
    return result; 
    } 
}); 

/client/myapp.js 
var q = Meteor.call('abc'); 
console.log(q); 

此結構返回到控制檯undefined

如果我改變myapp.js文件:

Meteor.call('abc', function(err, data) { 
    !err ? console.log(data) : console.log(err); 
} 

我收到Object在我的控制檯。

理想的情況下,這是希望我能夠做的,但它不工作,在控制檯中指出:Cannot read property 'greeting' of undefined

/client/myapp.js 
var q = Meteor.call('abc'); 

Template.hello.greeting = function() { 
    return q.foo; 
} 

從服務器對象傳送數據到任何幫助模板將不勝感激。我仍然在學習JavaScript流星&。

謝謝!

回答

77

the Meteor.call documentation

在客戶端,如果不傳遞一個回調,你是不是末節裏,調用將返回undefined,你將沒有辦法獲得的返回值方法。這是因爲客戶端沒有光纖,所以實際上沒有任何方法可以阻止遠程執行方法。

所以,你想要做這樣的:

Meteor.call('abc', function(err, data) { 
    if (err) 
    console.log(err); 

    Session.set('q', data); 
}); 

Template.hello.greeting = function() { 
    return Session.get('q').foo; 
}; 

這一次的數據是可用的被動會更新模板。

+1

湯姆你好,非常感謝您的快速反應!我不得不使用';;'關閉你的Meteor.call函數'並在'Template.hello.greeting'函數末尾追加一個分號,以使它最終能夠工作(如果你想編輯你的代碼)。再次感謝你的幫助! – rs77

+0

哦,woops,小錯誤,更正了答案。玩得開心...... :) –

+1

嗨湯姆,快速的問題 - 如果數據不會長期改變,有沒有辦法做到不必使用會話對象?隨着變量數量的增加,看起來非常浪費和冗長。謝謝。 –

1

發生這種情況是因爲Npm.require具有異步行爲。這就是你必須爲Meteor.call寫一個回調的原因。

但有一個解決方案,只需使用install(mrt add npm),您將得到一個名爲Meteor.sync(//...)的函數,您可以在Meteor.call()中同時執行這兩種遊戲:同步和異步。

參考:http://www.sitepoint.com/create-a-meteor-app-using-npm-module/

0

您可以通過使用reactive variable得到一個流星方法在模板使用的返回值。退房working demonstration on Meteorpad

+0

Meteorpad中的示例對我無效。此外,部署該示例工作...排序。也就是說,它只工作一次,但對我來說,當底層信息更新時,方法不會被調用。 – MastaBaba

+1

方法本身並不具有反應性,但可以從被動的上下文中調用,例如Template.instance()。autorun()或模板助手。 –

0

我去了貧民窟的解決方案。但是,它適用於我,這對我來說很重要。下面是我的代碼,我認爲它的概念解決了OP的問題。

在客戶端的main.js:

Meteor.setInterval(function() { 
    confirmLogin(); 

}, 5000); 

這將運行每五秒鐘confirmLogin()函數。

的confirmLogin功能(在客戶端的main.js):

function confirmLogin() { 
    Meteor.call('loggedIn', function (error, result) { 
     Session.set("loggedIn", result); 
    }); 

} 

的的loggedIn方法(在服務器的主。JS):

loggedIn: function() { 
    var toReturn = false; 
    var userDetails = Meteor.user(); 
    if (typeof userDetails["services"] !== "undefined") { 
     if (typeof userDetails["services"]["facebook"] != "undefined") { 
      toReturn = true; 
     } 
    } 

    return toReturn; 
}, 

相關助手:

loggedIn: function() { 
    return Session.get("loggedIn"); 
}