jco*_*fey 6 javascript javascriptmvc backbone.js
我的一些观点需要将他们的textareas转换为富文本编辑器.
我正在使用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
}
Run Code Online (Sandbox Code Playgroud)
如果您使用JQuery LiveQuery 插件附加编辑器会怎么样?此类代码可以是模板代码的一部分,但不是作为 HTML,而是作为与模板关联的 Javascript。或者您可以在全球范围内添加它。代码可能如下所示(假设您已包含插件本身):
$('textarea.wysiwyg').livequery(function() {
$(this).wysiwyg();
});
Run Code Online (Sandbox Code Playgroud)
我还没有测试过这段代码,但理论上,当它出现在 DOM 中时,它应该将 textarea 元素的实例与“wysiwyg”类相匹配,并调用 wysiwyg 函数来应用编辑器。
| 归档时间: |
|
| 查看次数: |
1358 次 |
| 最近记录: |