2015-10-24 20 views
0

Backbone.js代碼示例中的this屬性函數是如何工作的?這個代碼中的「this」函數是如何起作用的骨幹樣本?

由於代碼中未指定use strict指令,並且沒有對象傳遞給任何函數,Backbone.js代碼是否默認爲全局應用程序對象,或者它是否執行其他操作?

我假設this.render()可能呈現給通過下劃線模板傳入的el屬性指定的DOM元素,但this.$el.html

<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> 
<div id="search_container"> </div> 
<script type="text/javascript"> 
    var 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> 
+2

永遠記得縮進和評論你的代碼...也不要忘了今晚刷牙。不要任何額外的牙科賬單。 –

+2

我試圖但我的手機拒絕合作。你爲什麼要付牙醫賬單? –

回答

2

在此代碼示例this是指針SearchView的實例視圖。

您可以創建該視圖的許多實例,並且每個實例都會有this指向自己。


每個視圖實例都有兩個屬性指向該視圖實例的DOM元素。 .el指向DOM元素,.$el是指向該DOM元素的jQuery對象。

.$el的好處是你可以在該對象上調用任何jquery methods

因此this.$el.html()表示您在該視圖實例的DOM元素上調用jQuery.html method

在您的代碼中,您編譯了該視圖的模板並將其傳遞到$el.html(),該模板將模板的HTML插入到該視圖的DOM元素中。


至於initializethis.render(),它只是在此刻調用該實例的方法render當實例被初始化,也就是你看到的new關鍵字。新實例創建後,將自動調用initialize方法,該方法調用this.render()

例如,您可以在腳本的最後一行之後直接呼叫search_view.render(),而不是在initialize中調用this.render()