Meteor methods call apply 使用

来源:互联网 发布:大数据 医学的统计 编辑:程序博客网 时间:2024/05/18 00:03

在meteor中如果想在本地添加数据呢,

可以用:

var id=posts.insert(data);

data._id=id;

Router.go('Xx',data);

这种本地添加数据并不是一个太好的选择。

meteor为我们提供了一个methods call apply这些方法,可以让我们实现本地提交数据到指定方法。

服务器接收数据并return 结果,本地回调去获取。

有点类似于ajax 提交处理。

在服务端:

Meteor.methods({
'test':function(name){
console.log(name);
return {
name:'return '+name
}
},
'postInsert':function(post){
console.log(post);
var id=posts.insert(post);
return {
_id:id
};
}
});

这样来创建接口。

客户端:

Meteor.call('postInsert', post, function(error, result) {       
            if (error){
                return alert(error.reason);
            }  
            // show this result but route anyway
            if (result.postExists){
                alert('This link has already been posted');
            }
            Router.go('postPage', {_id: result._id});  
  });

这样来提交数据并获取结果。


其实服务端可以调用自己创建的接口,但并无多大用处。

Meteor.startup(function(){
var s=Meteor.call('test','server');
console.log(s);
Meteor.call('test','a',function(err,result){
console.log(result);
})


})


0 0