我的一些观点需要将它们的文本区域转换为富文本编辑器。
我使用 jwysiwyg 作为编辑器。它要求它所附加的元素在编辑器初始化时位于页面中,即当我调用 $(this.el).wysiwyg() 时,this.el 已经在文档中。
我的大多数视图实际上并没有附加到 dom - 他们的渲染方法只是使用应用程序模板引擎设置他们的元素 html 内容,例如 $(this.el).html(this.template(content)
在将这些子视图实际插入页面后,视图/控制器会进一步向上查看。同时,视图会在模型更改时重新渲染自己。
如何确保每次渲染时都将编辑器附加到元素,并且仍然确保在元素已经在页面中之前不附加编辑器?
显然,我可以一起破解一些适用于这种特殊情况的东西,但我想要一个适用于所有情况的优雅解决方案。
任何帮助将非常感激。
编辑:这里的要点是解决方案必须优雅地扩展以覆盖渲染后必须设置样式的多个元素,并且在它们位于 DOM 中之前不得设置样式
编辑:如果我进行自上而下渲染,这不是问题,但这很慢,我想要一个解决方案,我可以从下向上渲染,然后在顶部一次性插入完整视图
编辑:
结合使用下面建议的一些技术,我正在考虑执行以下操作。任何评论/批评将不胜感激。
app/views/base_view.js:
initialize: function() {
// wrap the render function to trigger 'render' events
this.render = _.wrap(this.render, function() {
this.trigger('render')
});
// bind this view to 'attach' events.
// 'attach' events must be triggered manually on any view being inserted into the dom
this.bind('attach', function() {
this.attached();
// the refreshed event is only attached to the render event after the view has been attached
this.bind('render', this.refreshed())
// each view must keep a record of its child views and propagate the 'attach' events
_.each(this.childViews, function(view) {
view.trigger('attach')
})
})
}
// called when the view is first inserted to the dom
attached: function() {
this.style();
}
// called if the view renders after it has been inserted
refreshed: function() {
this.style();
}
style: function() {
// default styling here, override or extend for custom
}