簡體   English   中英

Backbone.js el錯誤

[英]Backbone.js el error

我目前仍在學習boneer.js,但仍然很早就出錯了:

Uncaught TypeError: Cannot call method 'html' of undefined  

此this。$ el.html(template);

<body>
                <div id="search_container"></div>
                <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
                <script src="http://ajax.cdnjs.com/ajax/libs/json2/20110223/json2.js"></script>
                <script src="http://ajax.cdnjs.com/ajax/libs/underscore.js/1.1.6/underscore-min.js"></script>
                <script src="http://ajax.cdnjs.com/ajax/libs/backbone.js/0.3.3/backbone-min.js"></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">
                        $(document).ready(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 );
                                }
                                });

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

為什么會發生此錯誤?

您正在將視圖的el元素設置為

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

但是html中沒有元素已經存在。 這是導致錯誤的原因,用這種方式定義el意味着您已經在頁面上存在該元素,並將該元素分配為視圖的容器。

將該元素添加到HTML或按如下所示進行編輯

new SearchView();

因此默認情況下, el會退回到div。

當您在JavaScript代碼中引用DOM元素時,該元素必須已經可用-JS代碼應在此元素創建后運行。 在這里,您在腳本執行后創建了要向視圖的el字段#search_container div。 為了避免此類問題,請使用jQuery的ready方法:

$(document).ready(function()
{
    SearchView = Backbone.View.extend({

        // ...

    });

    // ...
});

在創建HTML文檔並准備使用所有元素之后,此方法將運行作為參數傳遞的函數。

另外,您使用的主干版本似乎無法自動管理$el屬性的值。 如果您需要使用此版本,請像下面這樣更新initialize方法:

initialize: function()
{                                  
    this.$el = $(this.el);
    this.render();
},

這將手動將$el設置$el所需值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM