UEditor:
UEditor - 首页
http://ueditor.baidu.com/website/
我们在对话框上放了几个 UEditor,发现第一次弹出对话框时UEditor还没有初始化 setContent 不能成功,于是加了一个 setTimeout 反复重试,后来发现关闭对话框后再打开还是不能正确的设置上去,原因是元素没有显示,遂有如下代码:
(function setTitle(){
var edt = UE.getEditor("title");
if(edt == null || $(edt.body).is(':visible') == false){ // 不断重试到初始化并且可见
setTimeout(setTitle, 10);
return;
}
edt.ready(function(){ // 当 ready 时才能真正 setContent
this.setContent(tr.data("title"));
this.removeListener('ready', arguments.callee)
});
})();
之后,撸起袖子将其封装为一个 MOLECULE:
<div molecule-def="UEditor">
<script>
// MOLECULE_DEF
function UEditor(){
// 创建UIEditor......
var me = this;
function updateContent(){ // 基本照抄上面的 updateTitle
var edt = UE.getEditor(me.el);
if(edt == null || $(edt.body).is(':visible') == false){
setTimeout(updateContent, 10);
return;
}
edt.ready(function(){
this.setContent(me.value);
this.removeListener('ready', arguments.callee)
});
}
this.setValue = function(v){
this.value = v;
updateContent();
}
this.getValue = function(){
var edt = UE.getEditor(this.el);
return edt ? edt.getContent() : this.value;
}
}
// MOLECULE_DEF_END
Molecule.create(UEditor)
</script>
</div>
该MOLECULE将值存放在 this.value 中,并包装了延迟设置逻辑,可以确保总能将值设置成功。
molecule 的两个函数命名为 getValue setValue,可以适配 d2js 前端渲染器 molecule 和收集器 m。
这个例子充分展示了 molecule 研发周期短,学习难度小的特点,从实现功能的 js 到 molecule 中的脚本块跳跃轻松,基本抄过去就形成了组件。