using setElement with views in backbone

2019-01-21 11:20发布

Following this tutorial went okay but I decided to give it another run with backbone 0.9 and the new setElement command.

<script type="text/javascript" id = "test" >
    SearchView = Backbone.View.extend({
        initialize: function(){ 
            this.render();
        },
        render: function(){
            var template = _.template( $("#search_template").html(), {} );

     //Right here

            this.setElement( template );

        },
        events: {
            "click input[type=button]": "doSearch"
        },
            alert( "Search for " + $("#search_input").val() );
        }
    });

    var search_view = new SearchView({ el: $("#search_container") });
</script>

Previously, I used this.el.html(template), but how do I use the new setElement command?

What I have there currently doesn't work, the search field that should appear does not.

1条回答
兄弟一词,经得起流年.
2楼-- · 2019-01-21 12:06

From the Backbone.js v0.9 documentation:

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.

The Backbone View "el" property represents the html portion of the view that will actually be rendered to the page. To get the view to actually render to the page your view will need to add it as a new element in the page or attach it to an existing element int the page.

The reason the code you used before worked was because you were setting the "el" property for the view in the constructor to attach to an existing element with an id of "search_container":

var search_view = new SearchView({ el: $("#search_container") });

The method you used before:

$(this.el).html(template);

worked because you were adding your template html to the existing element on the page.

When you used setElement in the following way:

this.setElement( template );

you were actually overriding your existing value for "el" from the element with id of "search_container" to the html of your template. And since your template has not been added to the page or doesn't already exist your view will not display.

If you want to still use setElement and continue attaching it to the id "search_container", I would call it when you initialize your view:

initialize: function(){ 
  this.setElement( this.el );
  this.render();
}

This way you can cached "$el" reference later, like so:

render: function(){
  var template = _.template( $("#search_template").html(), {} );
  this.$el.html(template);
}

Hope this helps!

查看更多
登录 后发表回答