Question

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);
Was it helpful?

Solution 2

Thank you, nimgrg, that worked with a tiny modification:

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

OTHER TIPS

When setting up the event, bind it like this:

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

Set context to the value object you want to be the "this" on the callback.

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top