backbone.js / underscore.js innerHTML而不是html()

时间:2012-05-15 09:56:57

标签: jquery backbone.js underscore.js

我正在使用backbone.js,underscore.js和jQuery。我从http://jsfiddle.net/thomas/C9wew/6/获取了以下示例代码:

<!DOCTYPE html>
<html>
    <head>
        <title>backbone.js</title>
    </head>
    <body>
        <div id="search_container">
            Container
        </div>

        <script src="/js/jquery-1.7.2.min.js" type="text/javascript" charset="utf-8"></script>
        <script src="/js/underscore-min.js" type="text/javascript" charset="utf-8"></script>
        <script src="/js/backbone-min.js" type="text/javascript" charset="utf-8"></script>

        <script type="text/template" id="search_template">
            <label>Search</label>
            <input type="text" id="search_input" />
            <input type="button" id="search_button" value="Search" />
        </script>

        <script type='text/javascript'>
            //<![CDATA[
            $(window).load(function() {

                SearchView = Backbone.View.extend({
                    initialize : function() {
                        this.render();
                    },
                    render : function() {
                        // Compile the template using underscore
                        var template = _.template($("#search_template").html(), {});
                        // Load the compiled HTML into the Backbone "el"
                        //this.el.html(template);
                        this.el.innerHTML = template;
                    },
                    events : {
                        "click input[type=button]" : "doSearch"
                    },
                    doSearch : function(event) {
                        // Button clicked, you can access the element that was clicked with event.currentTarget
                        alert("Search for " + $("#search_input").val());
                    }
                });

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

            });
            //]]>

        </script>
    </body>
</html>

我期待“el”成为jQuery包装元素,因为它是通过jQuery选择器$(“#search_container”)选择的,但不是因为它没有像html()这样的函数。

如果我在“el:$(”#search_container“)”行中设置断点,则“el”元素具有函数html(),这是正常行为。调用render函数时,“el”元素不再具有html()函数了。是什么意思?

1 个答案:

答案 0 :(得分:0)

您链接的示例基于旧版骨干网(0.3.3)。您的示例可能使用最新版本(0.9.2),其中this.el是DOM元素,this.$el是与this.el关联的缓存jQuery | Zepto元素。

这意味着如果您想使用html方法,请使用this.$el.html(template)。请查看此小提琴http://jsfiddle.net/gFcRR/1/以获取更新示例。