[]
每个单元格插件都包含“生命周期方法”,你可以重写这些方法,以便于在运行过程中特定的阶段执行这些方法。
单元格的生命周期调用顺序如下:
constructor()
createContent()
onPageLoaded()
destroy()
构造函数:constructor()
单元格类型被构造时调用,这个生命周期很少被使用到,偶尔用于初始化一下数据,没有特别的原因不推荐重写构造函数,如果重写,务必调用 super(...arguments) 来确保默认构造函数逻辑正确。
class MyPluginCellType extends Forguncy.Plugin.CellTypeBase {
constructor() {
super(...arguments);
this.initData = "test";
}
createContent() {
return $(`<div>${this.initData}</div>`);
}
}
Forguncy.Plugin.CellTypeHelper.registerCellType("MyPlugin.MyPluginCellType, MyPlugin", MyPluginCellType);
构建Dom结构 createContent()
大部分单元格会使用这个生命周期函数,用于创建单元格的Dom结构。活字格页面会按顺序调用每一个单元格的 createContent(), 这个函数需要返回一个Jquery 对象表示单元格的根 Dom 节点。活字格会把这个Dom节点挂入活字格的页面上。 在这个函数中,可以通过 this.CellElement.CellType.【属性名】获取单元格在设计时设置的属性值,也可以通过 this.CellElement.StyleInfo 获取单元格的样式设置。
class MyPluginCellType extends Forguncy.Plugin.CellTypeBase {
createContent() {
const prop = this.CellElement.CellType.MyProperty;
const color = this.CellElement.StyleInfo.Foreground;
const cssColor = Forguncy.ConvertToCssColor(color);
return $(`<div style='color:${cssColor}'>${prop}</div>`);
}
}
Forguncy.Plugin.CellTypeHelper.registerCellType("MyPlugin.MyPluginCellType, MyPlugin", MyPluginCellType);
页面加载完成onPageLoaded()
页面加载完成,会在页面数据初始化完成是调用。在页面初始化完成前,使用 this.evaluateFormula() 方法计算公式值,如果公式依赖了其他单元格的名称,可能会导致公式计算结果不正确。所以如果需要使用 this.evaluateFormula() 方法应该在这个函数中使用。
有些第三方类库在初始化时要求Dom必须已经挂载到Dom树上了,这种情况也应该把初始化逻辑写到 onPageLoaded 而不是 createContent中,因为createContent创建的Dom并没有挂载到Dom树上。
class MyPluginCellType extends Forguncy.Plugin.CellTypeBase {
content = null;
createContent() {
this.content = $("<div style='width:100%;height:100%;'></div>");
return this.content;
}
onPageLoaded() {
const prop = this.CellElement.CellType.MyProperty;
const result = this.evaluateFormula(prop)
this.content.text(result)
}
}
Forguncy.Plugin.CellTypeHelper.registerCellType("MyPlugin.MyPluginCellType, MyPlugin", MyPluginCellType);
单元格销毁destroy()
页面跳转导致离开当前页面,或者关闭弹出页面时,之前页面上所有单元格会调用destory()方法,常用于解除全局事件绑定。
关于 onLoad 函数
onLoad是活字格早期版本的生命周期,调用时机是所有单元格的Dom已经挂载到了Dom树上,但是页面的数据,计算引擎等没有初始化完成的时机。设计初衷是为了解决第三方类库必须在Dom挂载后才能调用初始函数的问题。在新版活字格中,这个生命周期可以完全被onPageLoaded取代,不建议继续使用。
活字格目前没有计划删除 onLoad 函数,以便于确保对旧版本插件的兼容性。