javascript 模型更新时的主干渲染视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13956365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:18:16  来源:igfitidea点击:

Backbone Render View on model update

javascriptbackbone.js

提问by Tamil

I'm writing a sample app using backbone.js.

我正在使用backbone.js 编写一个示例应用程序。

On update of my model I re-render my view in this fashion

在我的模型更新时,我以这种方式重新渲染我的视图

$('.target').html("");
$('.target').append(this.$el.html(this.template(model)))

Once the view is re-rendered after model update [on change event], events attached to the el's children gets lost [doesn't seem to be like jQuerylive]. Is this a known issue or am I missing something? Should I try to replace html instead of append? fiddle

一旦在模型更新后重新渲染视图 [on change event],附加到el孩子的事件就会丢失 [似乎不像jQuerylive]。这是一个已知问题还是我遗漏了什么?我应该尝试替换 html 而不是append小提琴

采纳答案by jevakallio

Once the view is in DOM, you don't need to keep removing and appending it. I think the simplest way to manage this is to remove the DOM insertion from the view altogether, and let the caller of view.renderto take care of it.

一旦视图在 DOM 中,您就不需要继续删除和附加它。我认为管理这个最简单的方法是从视图中完全删除 DOM 插入,让调用者view.render来处理它。

View:

看法:

render: function() {
  this.$el.html(this.template(model));
  return this;
}

Caller (on first render):

调用者(在第一次渲染时):

var view = new SomeView();
$('.target').append(view.render().el);

On subsequent renders:

在后续渲染中:

view.render();

After the view has been rendered into DOM it can keep happily re-rendering itself without having to know anything about parent views. The event bindings should also stay intact between renders.

在视图被渲染到 DOM 之后,它可以继续愉快地重新渲染自己,而无需知道任何关于父视图的信息。事件绑定也应该在渲染之间保持完整。