bebraw
5/21/2011 - 7:09 AM

"this" question material (JSShaper).

"this" question material (JSShaper).

"use strict"; "use restrict";

var Shaper = Shaper || require("shaper.js") || Shaper;

Shaper("this", function(root) {
    return Shaper.traverseTree(root, {
        pre: function(node, ref) {
            var prefix = '_.';
            var childThisName = 'that';
            var expr = Shaper.parseExpression(prefix + '$');

            if(Shaper.match(expr, node)) {
                var thisExpr = Shaper.parseExpression(childThisName + '.$');
                
                Shaper.replace(thisExpr, node.children[1]);
                Shaper.cloneComments(thisExpr, node);

                return ref.set(thisExpr);
            }
        }
    });
});
// current input
var Button = new Class({
    initialize: function() {
        this.color = 'blue';
        
        this.on('click', function() {
            _.color = 'red';
        })
    }
});

// desired input
var Button = new Class({
    initialize: function() {
        this.color = 'blue';
        
        this.on('click', function() {
            _color = 'red';
        })
    }
});
// current result
var Button = new Class({
    initialize: function() {
        this.color = 'blue';
        
        this.on('click', function() {
            that.color = 'red';
        })
    }
});

// desired result
var Button = new Class({
    initialize: function() {
        var that = this;
        this.color = 'blue';
        
        this.on('click', function() {
            that.color = 'red';
        })
    }
});