【问题标题】:Backbone listenTo and 'this' context骨干listenTo和'this'上下文
【发布时间】: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


【解决方案1】:

设置事件时,像这样绑定:

object.on(event, callback, [context])

将上下文设置为您希望在回调中成为“this”的值对象。

见:http://backbonejs.org/#Events-on

【讨论】:

  • 这就是我在这里尝试的:this.canvas.on('mouse:down', this.myFunction, this);没用...
【解决方案2】:

谢谢你,nimgrg,做了一个小小的修改:

this.canvas.on('mouse:down', this.myFunction.bind(this));

【讨论】:

    猜你喜欢
    • 2014-06-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    相关资源
    最近更新 更多