我有一个Backbone视图,我在那里听一个事件' mouse:down'由视图的canvas变量触发,该变量包含一个结构Canvas对象。该事件会触发函数' myFunction',并且在我需要使用的函数内部'这个'引用视图实例。请参阅以下代码:
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;
});
&#39; myFunction的&#39;被触发,但现在&#39;这个&#39;引用canvas对象,而不是视图实例。我怎样才能解决这个问题?我需要调用来自&#39; myFunction&#39;的视图的其他功能,但我现在很困扰......
我也试图将我的事件监听器更改为:
this.canvas.on('mouse:down', this.myFunction, this);
答案 0 :(得分:0)
设置事件时,请按以下方式绑定:
object.on(event, callback, [context])
将上下文设置为您希望成为&#34;此&#34;的值对象。在回调上。
答案 1 :(得分:0)
谢谢你,nimgrg,它做了一个微小的修改:
this.canvas.on('mouse:down', this.myFunction.bind(this));