I have a Backbone view where I listen for an event 'mouse:down' triggered by the view's canvas variable, which holds a fabric Canvas object. The event triggers the function 'myFunction', and inside the function I need to use 'this' to reference the view instance. See code below:
define([
'underscore',
'backbone',
'mustache',
'fabric'
], function(_, Backbone, Mustache, fabric) {
var MyView = Backbone.View.extend({
template: '<canvas id="my-canvas"></canvas>',
tagName: 'div',
id: 'my-id',
initialize: function () {
Mustache.parse(this.template);
},
render: function () {
this.$el.html(Mustache.render(this.template));
this.initCanvas('my-canvas');
return this;
},
initCanvas: function (canvasId) {
var canvas = new fabric.Canvas(canvasId, {
hoverCursor: 'pointer',
selection: false,
allowTouchScrolling: true,
width: 1170,
height: 658
});
fabric.Image.fromURL('myimage.jpg', function (img) {
canvas.setBackgroundImage(img);
canvas.renderAll();
});
this.canvas = canvas;
this.initCanvasListeners();
},
initCanvasListeners: function () {
this.listenTo(this.canvas, 'mouse:down', this.myFunction);
},
myFunction: function (options) {
console.log(this); // Outputs the canvas object, not MyView
}
});
return MyView;
});
'myFunction' is triggered, but now 'this' references the canvas object, not the view instance. How can I fix this? I need to call other functions of the view from 'myFunction', but I am quite stuck right now...
I have also unsuccessfully tried to change my event listener to look like this:
this.canvas.on('mouse:down', this.myFunction, this);