2014-10-31 26 views
0

我正在使用樹結構,所以我需要做一些漂亮的wonkey發現,只要我想從樹葉到樹幹工作,但我基本上試圖創建一個函數,我可以傳遞一個函數並應用/調用/綁定/一些原始上下文,以便我可以看到最初的變量。解釋會很棒。在骨架模型/集合中的Javascript範圍問題

layerListView = Backbone.Marionette.CollectionView.extend({  
    updateSelectedModelsInTree: function() { 
     var col = myApp.request('someOtherCollection'); 
     this.collection.startFromLeaves(function (m) { 
      this.updateSelected(m); 
      // col is undefined in here 
     }, this); 
    } 
}); 
layerCollection = Backbone.Collection.extend({ 
    startFromLeaves: function (doToModel, context) { 
     if (!this.models) return; 
     for (var i = this.models.length - 1; i >= 0; i--) { 
      var model = this.models[i], 
       tag = this.models[i].get('tag'); 
      if (tag == 'branch') this.startFromLeaves(arguments); 
      doToModel.call(context, model); 
     } 
    } 
}); 

所以我在這裏卡住了,和所有我想要做的是能夠看到被傳遞到startFromLeaves頂部函數內山坳變量。我不知道如何使用call/bind/apply,但我猜測我的上下文就是拋開所有東西。

+0

'col'應該是可見的存在,你確定'對myApp。請求('someOtherCollection')'沒有返回'undefined'? – 2014-10-31 02:28:27

+0

它絕對是返回它應該的集合。只是這樣,只要我進入我從startFromLeaves傳遞過來的函數內部,它就不存在 – 2014-10-31 02:31:17

+0

但是'col'是通過閉包抓取的,它與'this'或者上下文或者類似的東西沒有任何關係。演示的任何機會?我猜你的問題中的代碼並不是講完整個故事。 – 2014-10-31 02:37:53

回答

0

檢查出underscore.js

綁定功能,這樣您就可以通過具有此背景下設置的功能。因此,舉例來說,你可以做

updateSelectedModelsInTree: function() { 
    var col = myApp.request('someOtherCollection'); 
    this.collection.startFromLeaves(_.bind(function (m) { 
     this.updateSelected(m); 
     // col is undefined in here 
    }, this)); 
} 

「這個」內您的功能現在將永遠是「這個」包含「updateSelectedModelsInTree」