Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backbone js: How to remove extra tag in view?

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?

like image 789
firebird Avatar asked Feb 02 '23 13:02

firebird


2 Answers

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.

like image 182
Brian Genisio Avatar answered Feb 11 '23 08:02

Brian Genisio


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;
}
like image 42
Jeremy Zerr Avatar answered Feb 11 '23 07:02

Jeremy Zerr