[英]How to get data from meteor server in events with Meteor.js?
我想在事件中獲取流星服務器的數據或文檔。 有人對此有其他解決方案。
// meteor in server
Meteor.methods({
findPost: function() {
return Post.find().fetch();
}
}
});
//client template
<template name="Demo">
<input type="text" id="input-test">
<button id="test">Test</button>
</template>
//client event
Template.Demo.events({
'click #test':function(){
Meteor.call('findPost',function(error,result){
if(result) {
Session.set('foundPosts',result);
}
}
var posts=Session.get('foundPosts');
if(posts.length>0){
$('#input-test').val('Found');
}else{
$('#input-test').val('No result');
}
}
});
在此示例中,我使用會話獲取流星方法回調函數的值,以便可以使用它在方法回調函數之外執行其他操作。 有人在模板事件中有更好的解決方案從方法回調函數中獲取價值,還是有其他解決方案從流星服務器獲取數據。
Template.Demo.onCreated(function () {
this.inputValue = new ReactiveVar('No result');
})
Template.Demo.events({
'click #test': function () {
var tmpl = Template.instance();
Meteor.call('findPost', function (err, res) {
if (!err && res.length > 0) {
tmpl.inputValue.set('Found');
}
});
}
});
Template.Demo.helpers({
inputVal: function () {
var tmpl = Template.instance();
return tmpl.inputValue.get();
}
});
//client template
<template name="Demo">
<input type="text" id="input-test" value="{{inputVal}}">
<button id="test">Test</button>
</template>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.