前面介绍完主文件的加载机制,现在就可以进行Block区块主文件的编码开发了

main.js

src/suite-vendor/test-party/modules/test-party/backend/static/blocks/blockArticleCommentCount/main.js

  1. 1(function (global, factory) {
  2. 2 /* eslint-disable */
  3. 3 typeof exports === 'object' && typeof module !== 'undefined'
  4. 4 ? (module.exports = factory())
  5. 5 : typeof define === 'function' && define.amd
  6. 6 ? define(factory)
  7. 7 : null;
  8. 8 /* eslint-enable */
  9. 9})(this, function () {
  10. 10 class Block {
  11. 11 constructor(host) {
  12. 12 this.host = host;
  13. 13 this.timerId = 0;
  14. 14 }
  15. 15
  16. 16 async render() {
  17. 17 const { $util } = this.host;
  18. 18 const title = $util.text('Article Comment Count');
  19. 19 return `
  20. 20 <div class="article-comment-count">
  21. 21 <span class="title">${title}</span>
  22. 22 <span class="count"></span>
  23. 23 <span class="date"></span>
  24. 24 </div>`;
  25. 25 }
  26. 26
  27. 27 async mount() {
  28. 28 const { $content } = this.host;
  29. 29 // load css
  30. 30 await this._loadCSS();
  31. 31 // start timer
  32. 32 const interval = $content.interval;
  33. 33 this.timerId = window.setInterval(async () => {
  34. 34 await this._fetchAndShow();
  35. 35 }, interval);
  36. 36 }
  37. 37
  38. 38 async unmount() {
  39. 39 if (this.timerId) {
  40. 40 window.clearInterval(this.timerId);
  41. 41 this.timerId = 0;
  42. 42 }
  43. 43 }
  44. 44
  45. 45 ...
  46. 46 }
  47. 47 return Block;
  48. 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. 1$ npm run cli :tools:babel {blockPath}/main.js

举例:

  1. 1$ npm run cli :tools:babel src/suite-vendor/test-party/modules/test-party/backend/static/blocks/blockArticleCommentCount/main.js