2013-07-17 148 views
1

我努力學習Backbone.js的。 在我的應用程序,它使用與骨幹RequireJS,我有以下的代碼;瞭解Backbone.js的概念

define([ 
    'base/BaseView', 
    'model/BaseModel', 
    ], function(BaseView, 
     BaseModel){ 
     var myView = BaseView.extend({ 
      initialize: function() { 
       this.Summary = new resultSummary({ 
        scenId : this.options.scenario.get("scenId") 
       }); 
      }, 
      renderCount : function(){ 
       var self = this; 
       var currentStatus = self.model.get("myStatus"); 
      } 
      render: function() { 
      var self = this; 
      var gridItems = []; 
      gridItems.push({ 
        id: "company.status", 
        text: "Status", 
        width: "200px", 
        renderer: function() { 
         var partnerStatus = this.company.get("status"); 
        } 
      });  
      } 
     } 
    }); 

我不是很清楚一些概念;

  1. 究竟會「這一」表示,當我們說無功自我=這(我想,當我們使用「這個」隨處JS代碼來理解這是一個普遍的問題,以及意)
  2. 不「這種」改變,如果我們現在需要在初始化Vs的,當我們在renderCount Vs的,當我們在‘渲染’,在上面的代碼?
  3. 的代碼 「this.company.get(」 狀態 「)」,究竟是什麼this.company代表什麼?這是指模型嗎?
+0

這是否代碼工作的一些財產? –

+0

它實際上只是實際工作代碼的表示形式。 – testndtv

+0

此問題與JavaScript概念有關,比骨幹網更多。 – mor

回答

2

我想你問封閉?

我們分配

var self = this; 

,所以我們可以保留嵌套函數內部類的範圍。在這種情況下:

renderer: function() { 
        var partnerStatus = this.company.get("status"); 
       } 

這裏是一個偉大的閱讀:"Closures - JavaScript | MDN"

2

我可能會不能夠回答所有的問題,因爲有問題的代碼可能是從更大的代碼庫複製。

  1. 爲什麼我們使用VAR自我=這一點;這代表什麼時候執行上面的代碼?

var self = this;用於避免範圍問題。有時,當您使用回調時,可能會更改爲其他某個對象。代碼中提到的代碼不以任何方式受益可以直接使用。

例如當它是有用的 - 可以說,我們需要聽取模型的變化,我們要重視處理程序初始化方法和觀點上的變化需要一些邏輯:

// view code 
initialize: function() { 
    console.log(this); // 'this' points to view 
    this.listenTo(this.model, "change", function() { 
     console.log(this); // 'this' points to model 
     // calling 'this.someLogic();' would throw exception 
    }); 
}, 

someLogic: function() { 
    // .. 
} 

爲了避免問題在第一個例子中描述過,您需要將視圖上下文中的'this'存儲在其他變量中(不必命名爲self)。

改寫例如:

// view code 
initialize: function() { 
    console.log(this); // 'this' points to view 
    var self = this; // store this into variable that will won't be changed in different scope 
    this.listenTo(this.model, "change", function() { 
     console.log(this); // 'this' points to model 
     console.log(self); // 'self' points to view 
     self.someLogic(); // won't throw 
    }); 
}, 

someLogic: function() { 
    // .. 
} 

我建議你檢查在JavaScript關閉工作如何。它不僅適用於Backbone,而且適用於一般的JavaScript開發。

  1. 是否「這個」改變,如果我們都在裏面初始化Vs的,當我們在renderCount Vs的,當我們在「渲染」,在上面的代碼?

不,骨架會指向'this'來查看包含那些方法的對象。

  1. 的代碼 「this.company.get(」 狀態 「)」,究竟是什麼this.company代表什麼?這是指模型嗎?

不知道真的,我只能猜測,這是從基本視點