【发布时间】:2014-05-02 13:23:02
【问题描述】:
我有一个 Backbone 视图,我在其中侦听由视图的 canvas 变量触发的事件“mouse:down”,该变量包含一个织物 Canvas 对象。该事件触发函数“myFunction”,在函数内部我需要使用“this”来引用视图实例。见以下代码:
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' 被触发,但现在'this' 引用画布对象,而不是视图实例。我怎样才能解决这个问题?我需要从“myFunction”调用视图的其他功能,但我现在很卡住......
我也尝试将事件侦听器更改为如下所示,但未成功:
this.canvas.on('mouse:down', this.myFunction, this);
【问题讨论】:
-
你试过this.canvas.on('mouse:down', myFunction.bind(this));
-
你不能只做一个常规事件哈希吗?类似事件:{“mousedown canvas”:“myFunction”
标签: backbone.js backbone-views backbone-events