How do you dynamically create elements of the Backbone view?

I would like to create several view elements in the jbbbbbbbbbb application. When a new view is initialized, I want it to introduce a new item in the DOM, save the link to the item in view.el, and delegate events as usual.

I understand that I can put in my html and then customize the view with el: "#test", but this seems like an unnecessary image for modals and other views that are not central to the web application. Is there a prescribed way to do this, I'm missing from the docs? I just don't understand how submissions should work?

+6
source share
1 answer

The skeleton will generate el for you, without having to do anything. By default, a <div> . However, you can generate any tag name you want. After creating the instance of the view, implement the render method in the view and fill el with your 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 is common practice to use a templating system to render your HTML representation, such as Underscore.js, Handlebars, or any other dozens of JavaScript template templates.

When you have content created using a view, you need to paste it into the DOM somewhere before it is visible. This is usually done using jQuery or another plugin:

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

+8
source

Source: https://habr.com/ru/post/913129/


All Articles