2016-10-25 37 views
1

我有一個Backbone視圖,其中我將droppable設置爲一個元素。我想訪問'外部'addOperator方法但是如何?它給出了一個錯誤,說它不是一個函數。'functionInBackboneView'不是函數 - 在Jquery中的上下文

var CanvasView = Backbone.View.extend({ 
    el: "#canvas", 
    render: function() { 
     $("#canvas-container").droppable({ 
      drop: this.handleDropEvent 
     }); 
    }, 
    addOuterOdperator: function (toolID) { 
     console.log(toolID); 
     console.log("outer"); 
    }, 
    handleDropEvent: function (event, ui) { 
     console.log("inside handle func"); 
     var id = 0; 
     var addInnerOperator=function(ie){ 
      console.log("inner"); 
     }; 
     addInnerOperator(id); 
     //this.addOuterOperator(id); gives an errror 
    } 
}); 

回答

1

我相信你在this.addOuterOperator錯誤,因爲你在事件處理程序的上下文中。所以爲了避免你可能會嘗試下面的代碼:

var CanvasView = Backbone.View.extend({ 
    el: "#canvas", 
    render: function() { 
     var self = this; //creating a self reference 
     $("#canvas-container").droppable({ 
      drop: function(event, ui) { 
       self.handleDropEvent(event, ui, self); //passing the self reference 
      } 
     }); 
    }, 
    addOuterOdperator: function (toolID) { 
     console.log(toolID); 
     console.log("outer"); 
    }, 
    handleDropEvent: function (event, ui, selfRef) { 
     console.log("inside handle func"); 
     var id = 0; 
     var addInnerOperator=function(ie){ 
      console.log("inner"); 
     }; 
     addInnerOperator(id); 
     selfRef.addOuterOperator(id); //accessing the function via selfRef 
    } 
}); 
相關問題