【问题标题】:using setElement with views in backbone将 setElement 与主干中的视图一起使用
【发布时间】:2012-03-06 15:07:37
【问题描述】:

按照this 教程进行,一切正常,但我决定使用主干 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>

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

我那里的东西目前不起作用,应该出现的搜索字段也不起作用。

【问题讨论】:

    标签: javascript backbone.js underscore.js


    【解决方案1】:

    来自 Backbone.js v0.9 文档:

    设置元素

    view.setElement(element) 
    

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

    Backbone 视图的“el”属性表示将实际呈现到页面的视图的 html 部分。要让视图实际呈现到页面,您的视图需要将其添加为页面中的新元素或将其附加到页面中的现有元素。

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

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

    你之前使用的方法:

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

    之所以有效,是因为您将模板 html 添加到页面上的现有元素中。

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

    this.setElement( template );
    

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

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

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

    这样你以后可以缓存“$el”引用,像这样:

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

    希望这会有所帮助!

    【讨论】:

    • 您可以使用ui 映射中的元素以及setElement 吗?
    猜你喜欢
    • 2012-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-30
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多