【发布时间】:2011-09-15 03:41:48
【问题描述】:
我的一些视图需要将它们的文本区域转换为富文本编辑器。
我使用 jwysiwyg 作为编辑器。它要求它所附加的元素在编辑器初始化时在页面中,即当我调用 $(this.el).wysiwyg() 时,this.el 已经在文档中。
我的大多数视图实际上并没有附加到 dom - 他们的渲染方法只是使用应用程序模板引擎设置他们的元素 html 内容,例如$(this.el).html(this.template(content)
在实际将这些子视图插入页面后,视图/控制器进一步向上查看。同时,视图会在模型发生变化时重新渲染自己。
如何确保每次渲染时都将编辑器附加到元素上,并且仍然确保在元素已经在页面中之前不附加编辑器?
显然我可以一起破解一些适用于这种特殊情况的东西,但我想要一个适用于所有情况的优雅解决方案。
任何帮助将不胜感激。
编辑:这里的要点是解决方案必须优雅地缩放以覆盖渲染后必须设置样式的多个元素,并且在它们位于 DOM 之前不得设置样式
编辑:如果我进行自上而下渲染,这不是问题,但这很慢,我想要一个解决方案,我可以从下向上渲染,然后在顶部一次性插入完整视图
编辑:
结合使用下面建议的一些技术,我正在考虑执行以下操作。任何 cmets/批评将不胜感激。
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
}
【问题讨论】:
-
结果如何?找到合理的解决方案了吗?
-
好吧,我最终使用了上面编辑中的代码,它可以正常工作。我将把赏金奖励给strongriley,因为他的答案最接近我最终得到的答案。尽管我不确定自己的解决方案,但会暂时搁置这个问题
-
很公平。我很好奇您是否尝试过我看起来最干净的答案。我不想在每个可能有文本区域的视图中放置包装代码;基本上,我希望它“正常工作”。无论如何,好问题,喜欢它。
-
经过仔细检查 - 你是绝对正确的!这实际上是一个非常棒的插件。让我感到羞耻,但我实际上并没有检查出来,因为你提到它没有经过测试,我记得一段时间前曾尝试过一个非常相似的任务,它只是以与 jquery 的现场活动类似的方式运行。对赏金感到抱歉,因为这可以在一行代码中解决问题。
-
没问题;很高兴您找到了适合您的解决方案。
标签: javascript backbone.js javascriptmvc