在主干中使用带有视图的setElement

Vic*_*cVu 17 javascript backbone.js underscore.js

教程之后没问题,但我决定再次使用backbone 0.9和新的setElement命令运行它.

<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>
Run Code Online (Sandbox Code Playgroud)

以前,我用过this.el.html(template),但是如何使用新的setElement命令?

我目前所拥有的功能不起作用,应该出现的搜索字段不起作用.

sha*_*ren 48

从Backbone.js v0.9文档:

setElement

view.setElement(element) 
Run Code Online (Sandbox Code Playgroud)

如果您想将Backbone视图应用于其他DOM元素,请使用setElement,它还将创建缓存的$ el引用,并将视图的委托事件从旧元素移动到新元素.

Backbone View"el"属性表示将实际呈现给页面的视图的html部分.要使视图实际呈现到页面,您的视图需要将其添加为页面中的新元素,或将其附加到页面中的现有元素.

您之前使用的代码的原因是因为您在构造函数中为视图设置了"el"属性以附加到id为"search_container"的现有元素:

var search_view = new SearchView({ el: $("#search_container") });
Run Code Online (Sandbox Code Playgroud)

您之前使用的方法:

$(this.el).html(template);
Run Code Online (Sandbox Code Playgroud)

因为您将模板html添加到页面上的现有元素而工作.

当您以下列方式使用setElement时:

this.setElement( template );
Run Code Online (Sandbox Code Playgroud)

您实际上是将"el"的现有值从id为"search_container"的元素覆盖到模板的html.由于您的模板尚未添加到页面中或尚未存在,因此您的视图将不会显示.

如果你仍想使用setElement并继续将它附加到id"search_container",我会在初始化你的视图时调用它:

initialize: function(){ 
  this.setElement( this.el );
  this.render();
}
Run Code Online (Sandbox Code Playgroud)

这样你可以稍后缓存"$ el"引用,如下所示:

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

希望这可以帮助!