Wednesday, February 19, 2014

Raphael js - Uncaught TypeError: Cannot call method 'enable' of undefined

When enabling dragging in Raphael js, if you are using raphael-draggable, then you might run into following error when you try to enable the dragging on any element -

Uncaught TypeError: Cannot call method 'enable' of undefined

That line is -
 paper.draggable.enable() 

The issue is in Raphale 2.0 context is broken, and in order to fix that you have can add following function -

// to fix broken context issue with Raphael 2.0

Raphael.fn.fixNS = function(){

    var r = this;

    for (var ns_name in Raphael.fn) {

        var ns = Raphael.fn[ns_name];

        if (typeof ns == 'object') for (var fn in ns) {

            var f = ns[fn];

            ns[fn] = function(){ return f.apply(r, arguments); }

        }

    }

}
 
Once you add it, call that function below your Raphael block initialization -

var paper = new Raphael(obj.attr('id'), chart_width, chart_height);
    paper.fixNS();

This should be able to fix the issue and you will be able to enable dragging for individual element or your Raphael object.

paper.draggable.enable();