如果没有仔细看Meteor文档,可能对于远程调用 感觉无从下手。其实Meteor提供了很简单 的API 来完成这个功能
尊重劳动成功,转载请注明
见API Meteor.methods 部分 。
Meteor.methods(methods)
Defines functions that can be invoked over the network by clients.
定义函数 可以被客户端在网络上调用。
参数
-
methods
Object
-
Dictionary whose keys are method names and values are functions.
方法字典,key值是函数名,value值是函数体
例如
注意:如果方法有返回值, 应该返回一个 EJSON 类型 或者抛出个异常。Meteor.methods({ foo: function (arg1, arg2) { // .. do stuff .. if (you want to throw an error) throw new Meteor.Error(404, "Can't find my pants"); return "some return value"; }, bar: function () { // .. do other stuff .. return "baz"; } });
好了,服务端就这么写就可以了,在来看看客户端怎么调用服务端定义的方法
见API Meteor.call 部分
Meteor.call(name, param1, param2, ... [, asyncCallback])
这个方法可以在客户端和服务端 运用Invokes a method passing any number of arguments.
通过数个参数调用 一个方法
参数
-
name
String
-
需要调用方法的名字(定义在服务端的)
param1, param2, ...
EJSON
-
设置方法的参数
asyncCallback
Function
-
回调函数, 服务端function 运行完成后的异步回调函数,包含两个参数。err和result. 如果这个回调函数没有提供, 那么这个调用可能是同步的。
Meteor.call('foo', 1, 2, function (error, result) { ... } );
说了这么多 来写个实际能跑起来的例子
meteor create testfunctioncall
cd testfunctioncall
del * (window用del *,Linux 用 rm *) ##删除里面的三个文件 testfunctioncall.css testfunctioncall.js testfunctioncall.html
创建2个文件夹 client 和 server
在 client文件夹中 创建一个 test.html
内容如下:
<head> <title>test</title> </head> <body> {{> hello}} </body> <template name="hello"> <input type="button" value="ClickMe" id="abc"/> </template>
在创建一个test.jsTemplate.hello.events({ "click #abc":function(){ Meteor.call("hello","张三",function(err,result){ if(!err){ alert(result); } }); } });
客户端代码写好了 来写服务端代码在server文件夹里创建一个call.js
Meteor.methods({ hello: function(name) { console.log("hello"+ name); return "hello"+name; } })
完工!在终端 或着CMD 界面输入
meteor
然后打开浏览器 在地址栏 输入 http://localhost:3000
点击按钮 测试
-