# 模块
FXS 代码可以编写在fxml文件中的<fxs>标签内,或以.fxs为后缀名的文件内。
# 1. 模块
每一个.fxs文件和<fxs>标签都是一个单独的模块。
每个模块都有自己独立的作用域。即在一个模块里面定义的变量与函数,默认为私有的,对其他模块不可见。
一个模块要想对外暴露其内部的私有变量与函数,只能通过module.exports实现。
# .fxs 文件
在微信开发者工具里面,右键可以直接创建.fxs文件,在其中直接编写 FXS 脚本。
# 示例代码
// /pages/comm.fxs
var foo = "'hello world' from comm.fxs";
var bar = function(d) {
return d;
}
module.exports = {
foo: foo,
bar: bar
};
上述例子在/pages/comm.fxs的文件里面编写了 FXS 代码。该.fxs文件可以被其他的.fxs文件 或 FXML 中的<fxs>标签引用。
# module 对象
每个fxs模块均有一个内置的module对象。
# 属性
exports: 通过该属性,可以对外共享本模块的私有变量与函数。
# 示例代码
// /pages/tools.fxs
var foo = "'hello world' from tools.fxs";
var bar = function (d) {
return d;
}
module.exports = {
FOO: foo,
bar: bar,
};
module.exports.msg = "some msg";
<!-- page/index/index.fxml -->
<fxs src="./../tools.fxs" module="tools" />
<view> {{tools.msg}} </view>
<view> {{tools.bar(tools.FOO)}} </view>
页面输出:
some msg
'hello world' from tools.fxs
# require函数
在.fxs模块中引用其他fxs文件模块,可以使用require函数。
引用的时候,要注意如下几点:
- 只能引用
.fxs文件模块,且必须使用相对路径。 fxs模块均为单例,fxs模块在第一次被引用时,会自动初始化为单例对象。多个页面,多个地方,多次引用,使用的都是同一个fxs模块对象。- 如果一个
fxs模块在定义之后,一直没有被引用,则该模块不会被解析与运行。
# 示例代码
// /pages/tools.fxs
var foo = "'hello world' from tools.fxs";
var bar = function (d) {
return d;
}
module.exports = {
FOO: foo,
bar: bar,
};
module.exports.msg = "some msg";
// /pages/logic.fxs
var tools = require("./tools.wxs");
console.log(tools.FOO);
console.log(tools.bar("logic.wxs"));
console.log(tools.msg);
<!-- /page/index/index.fxml -->
<fxs src="./../logic.fxs" module="logic" />
控制台输出:
'hello world' from tools.fxs
logic.fxs
some msg
# <fxs> 标签
| 属性名 | 类型 | 默认值 | 说明 |
|---|---|---|---|
| module | String | 当前 <fxs> 标签的模块名。必填字段。 | |
| src | String | 引用.fxs文件的相对路径。仅当本标签为单闭合标签或标签的内容为空时有效。 |
# module 属性
module 属性是当前<fxs>标签的模块名。在单个 fxml 文件内,建议其值唯一。有重复模块名则按照先后顺序覆盖(后者覆盖前者)。不同文件之间的 fxs 模块名不会相互覆盖。
module 属性值的命名必须符合下面两个规则:
- 首字符必须是:字母(a-zA-Z),下划线(_)。
- 剩余字符可以是:字母(a-zA-Z),下划线(_), 数字(0-9)。
# 示例代码
<!--fxml-->
<fxs module="foo">
var some_msg = "hello world";
module.exports = {
msg : some_msg,
}
</fxs>
<view> {{foo.msg}} </view>
页面输出:
hello world
上面例子声明了一个名字为foo的模块,将some_msg变量暴露出来,供当前页面使用。
# src 属性
src 属性可以用来引用其他的fxs文件模块。
引用的时候,要注意如下几点:
- 只能引用
.wxs文件模块,且必须使用相对路径。 wxs模块均为单例,wxs模块在第一次被引用时,会自动初始化为单例对象。多个页面,多个地方,多次引用,使用的都是同一个wxs模块对象。- 如果一个
wxs模块在定义之后,一直没有被引用,则该模块不会被解析与运行。
# 示例代码
// /pages/index/index.js
Page({
data: {
msg: "'hello wrold' from js",
}
})
<!-- /pages/index/index.fxml -->
<fxs src="./../comm.fxs" module="some_comms"></fxs>
<!-- 也可以直接使用单标签闭合的写法
<fxs src="./../comm.fxs" module="some_comms" />
-->
<!-- 调用 some_comms 模块里面的 bar 函数,且参数为 some_comms 模块里面的 foo -->
<view> {{some_comms.bar(some_comms.foo)}} </view>
<!-- 调用 some_comms 模块里面的 bar 函数,且参数为 page/index/index.js 里面的 msg -->
<view> {{some_comms.bar(msg)}} </view>
页面输出:
'hello world' from comm.wxs
'hello wrold' from js
上述例子在文件/page/index/index.fxml中通过<fxs>标签引用了/page/comm.fxs模块。
# 2. 注意事项
<fxs>模块只能在定义模块的 FXML 文件中被访问到。使用<include>或<import>时,<fxs>模块不会被引入到对应的 FXML 文件中。<template>标签中,只能使用定义该<template>的 FXML 文件中定义的<fxs>模块。