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.
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?
New elements can be dynamically created in JavaScript with the help of createElement() method. The attributes of the created element can be set using the setAttribute() method.
With document. createElement() method you can create a specified HTML element dynamically in JavaScript. After creation you can add attributes. If you want the element to show up in your document, you have to insert in into the DOM-tree of the document.
Backbone. js is a model view controller (MVC) Web application framework that provides structure to JavaScript-heavy applications. This is done by supplying models with custom events and key-value binding, views using declarative event handling and collections with a rich application programming interface (API).
In backbone. js, there are 7 modules HTTP request, Router, View, Events, Model, and Collection. Whenever a user makes a request it is directed to the router and in response to these requests, a user interface is displayed at the user end which is known as Views. So basically View in backbone.
A backbone view will generate an el
for 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 render
method on the view, and populate the 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'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.
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:
$("#some-element").html(v2.el);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With