prasadKodeInCloud / meteor-client-debugger

Facilitates to debug client side codes of meteor
MIT License
9 stars 1 forks source link

Failed to extend helpers since cannot access variables defined out of scope #1

Closed prasadKodeInCloud closed 9 years ago

prasadKodeInCloud commented 9 years ago

I tried 3 different ways to override the template helpers to include console.log inside the function. Meteor version 0.8.1.3

Method 1 - Did not work at all.

 var helperFunc = Template[ tmpName ][ helper ];
 Template[ tmpName ][ helper ] = function(/* ...*/){
        if(console)
              console.log( tmpName, '- called helper : ', helper );
          helperFunc.apply( Template[ tmpName ], arguments ); 

   }  

Method 2 -Using Eval - Cannot access the variables defined in outside

var color = getRandomColor();
            var logMsg = "console.log('%c Called " + helper + " helper of template " + tmpName + " ' , 'font-size:12px; background:#E9F0B6; color: " + color + "');";
            var funcString = Template[ tmpName ][ helper ].toString();
            funcString = funcString.replace('{', '{@#$%^&*');
            var strArr = funcString.split('@#$%^&*');
            strArr[0] = strArr[0]  + logMsg;

            var newFuncString = '';
            for(var i = 0 ; i < strArr.length ; i++){
                newFuncString += strArr[i];
            }

            eval('var ' + tmpName + '_' + helper + ' = ' + newFuncString );
            Template[ tmpName ][ helper ] = eval( tmpName + '_' + helper );

Method 3 - Didnt work

var originalHelpersPrototype = Template.prototype.helpers;
Template.prototype.helpers = function ( dict ) {
    for (var k in dict){
        dict[k] = new Extender().extendedHelper(this.__templateName, k, dict[k]);
    }

    originalHelpersPrototype.apply( this, arguments );
};

Extender().extendedHelper: function( tmpName, helper, func ){
            var color = getRandomColor();
            return function(/* ...*/){
                if(Session.get('debug_template_helpers') === true ){
                    console.log('%c Called helper : "' + helper + '" of "' + tmpName + '" ', 'font-size:12px; background:#E9F0B6; color:' + color);
                }

                func.apply( this, arguments );
            }
arunoda commented 9 years ago

We did something similar. Check here: https://github.com/meteorhacks/zones/blob/master/assets/utils.js#L221

prasadKodeInCloud commented 9 years ago

Thanks for the reference. Checked with Zone code and issue was fixed adding these lines to method 1.

var result = helperFunc.apply( Template[ tmpName ], arguments ); 
 return result;