Meteor 客户端远程调用服务端函数

如果没有仔细看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值是函数体

例如

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";
  }
});

注意:如果方法有返回值, 应该返回一个   EJSON  类型  或者抛出个异常。


好了,服务端就这么写就可以了,在来看看客户端怎么调用服务端定义的方法

见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.js

Template.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

点击按钮 测试 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值