javascript 如何动态创建 Backbone 视图元素?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10140787/
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 08:48:46  来源:igfitidea点击:

How do you dynamically create Backbone view elements?

javascriptbackbone.jsbackbone-views

提问by chrisM

I'd like to create some view elements in a Backbone js application dynamically. When a new view is initialized, I want it to insert the new element into the DOM, store the reference to the element in view.el, and delegate events as usual.

我想在 Backbone js 应用程序中动态创建一些视图元素。当一个新视图被初始化时,我希望它把新元素插入到 DOM 中,在 view.el 中存储对元素的引用,并像往常一样委托事件。

I understand that I can put in my html, and then setup a view with el: "#test" but this seems like overkill for modals and other views that aren't central to the web application. Is there a prescribed way to do this I'm missing in the docs? Am I just misunderstanding how views are supposed to work?

我知道我可以放入我的 html,然后使用 el:"#test" 设置一个视图,但这对于模式和其他非 Web 应用程序核心的视图来说似乎有点过分了。有没有规定的方法可以做到这一点我在文档中遗漏了?我只是误解了视图应该如何工作吗?

回答by Derick Bailey

A backbone view will generate an elfor you, without you having to do anything. By default, it creates a <div>. You can generate any tag name you want, though. Once you have the view instantiated, implement a rendermethod on the view, and populate the elwith your HTML.

主干视图将为el您生成一个,而您无需执行任何操作。默认情况下,它会创建一个<div>. 不过,您可以生成任何您想要的标签名称。实例化render视图后,在视图上实现一个方法,并el用您的 HTML填充。


MyView = Backbone.View.extend({});

var v = new MyView();
console.log(v.el); // => "<div></div>"


// define your own tag, and render contents for it

MyTagView = Backbone.View.extend({
  tagName: "ul",

  render: function(){
    this.$el.html("<li>test</li>");
  }
});

var v2 = new MyTagView();
v2.render();
console.log(v2.el); // => "<ul><li>test</li></ul>"

It's common practice to use a template system to render your view's HTML, like Underscore.js template, Handlebars, or any of the other dozen or more template JavaScript template engines.

通常的做法是使用模板系统来呈现视图的 HTML,例如 Underscore.js 模板、Handlebars 或其他十几个或更多模板 JavaScript 模板引擎中的任何一个。

Once you have the content generated from the view, you need to stick it in to the DOM somewhere before it will be visible. This is usually done with jQuery or another plugin:

从视图中生成内容后,您需要将其粘贴到 DOM 中的某个地方,然后才能看到它。这通常是通过 jQuery 或其他插件完成的:

$("#some-element").html(v2.el);

$("#some-element").html(v2.el);