前面介绍完主文件的加载机制
,现在就可以进行Block区块主文件
的编码开发了
main.js
src/suite-vendor/test-party/modules/test-party/backend/static/blocks/blockArticleCommentCount/main.js
- 1(function (global, factory) {
- 2 /* eslint-disable */
- 3 typeof exports === 'object' && typeof module !== 'undefined'
- 4 ? (module.exports = factory())
- 5 : typeof define === 'function' && define.amd
- 6 ? define(factory)
- 7 : null;
- 8 /* eslint-enable */
- 9})(this, function () {
- 10 class Block {
- 11 constructor(host) {
- 12 this.host = host;
- 13 this.timerId = 0;
- 14 }
- 15
- 16 async render() {
- 17 const { $util } = this.host;
- 18 const title = $util.text('Article Comment Count');
- 19 return `
- 20 <div class="article-comment-count">
- 21 <span class="title">${title}</span>
- 22 <span class="count"></span>
- 23 <span class="date"></span>
- 24 </div>`;
- 25 }
- 26
- 27 async mount() {
- 28 const { $content } = this.host;
- 29 // load css
- 30 await this._loadCSS();
- 31 // start timer
- 32 const interval = $content.interval;
- 33 this.timerId = window.setInterval(async () => {
- 34 await this._fetchAndShow();
- 35 }, interval);
- 36 }
- 37
- 38 async unmount() {
- 39 if (this.timerId) {
- 40 window.clearInterval(this.timerId);
- 41 this.timerId = 0;
- 42 }
- 43 }
- 44
- 45 ...
- 46 }
- 47 return Block;
- 48});
-
行1-9:采用统一的规范同时支持
CommonJS/AMD
加载机制 -
行10:定义Block区块
Class
,并返回
Block区块Class
可按需提供如下方法,在合适的场景调用
名称 | 可选 | 场景 | 说明 |
---|---|---|---|
constructor | false | all | 创建实例时,传递场景的宿主对象 |
render | true | 后端输出/可视化编辑 | 用于输出HTML内容,适用于区块的静态功能 |
mount | true | all(后端输出例外) | 当HTML内容显示时执行自定义逻辑,适用于区块的动态功能 |
unmount | true | all(后端输出例外) | 当显示的HTML内容销毁时执行清理逻辑 |
main.min.js
当我们在开发阶段编辑完成main.js
之后,就需要编译生成main.min.js
,以便在生产环境使用
CabloyJS项目已经内置了npm script
指令,只需执行如下命令即可:
- 1$ npm run cli :tools:babel {blockPath}/main.js
举例:
- 1$ npm run cli :tools:babel src/suite-vendor/test-party/modules/test-party/backend/static/blocks/blockArticleCommentCount/main.js
评论: