I have the following template:
<div class="row">
<div></div>
....
</div>
and the following view:
var TestView = Backbone.View.extend({
tagName: "div",
template: $("#tests_template"),
initialize: function () {
_.bindAll(this, 'clickbtn');
},
events:
{
"click .btn": "clickbtn"
},
render: function () {
....
{
});
The problem is, it produces the following output:
<div><div class="row">...</div></div>
How do I get rid of the outer div? I tried removing the tagName property from the view but it still puts a div?
Change your template to get rid of the outer div:
<div></div>
....
Then, tell the view to create the div with a class name:
tagName: "div",
className: "row"
OR if you want to keep the current template, then tell the View which el
to use (assuming it exists already some place on your page):
var testView = new TestView({el: $(".row")});
EDIT You asked if you can do this in the initializer? Sure, but you'd need to make sure that you hook the events:
initialize: function () {
this.el = $(".row");
this.delegateEvents();
_.bindAll(this, 'clickbtn');
}
Honestly, though, the first two options are more de-coupled IMO.
Another option that does not require modifying the template is to use setElement
setElement view.setElement(element)
If you'd like to apply a Backbone view to a different DOM element, use setElement, which will also create the cached $el reference and move the view's delegated events from the old element to the new one.
This will allow you to completely bypass tagName. You can leave tagName out of your View definition (it defaults to div anyways). You also do not have to worry about manually delegating your events or require that an element selector is known beforehand as referred to in the answer by @Brian Genisio, although those other methods will work too.
render: function () {
this.setElement(this.template(this.model.toJSON()));
return this;
}
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