SachiDangalla SachiDangalla - 1 month ago 6
Javascript Question

'functionInBackboneView' is not a function - context in Jquery

I have a Backbone view where I set

droppable
to an element. I want to access the 'outer'
addOperator
method but how? It gives an error saying it is not a function.

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
}
});

Answer

I believe you are getting error with this.addOuterOperator because you are within event handler context. So to avoid that you may try below code:

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
    }
});
Comments