开发者

Attempting To Use MooTools and Raphael

I have the following piece of code which is not running as I expected:

var person = new Class({
    initialize: function(name)
    {
        this.personName = name;
        alert(this.personName)        //WORKS :-)

 开发者_Python百科       this.testFunc();              //WORKS :-)
        this.createShape();           //PAINTS SHAPE BUT CANNOT ACCESS 'personName'
    },
    testFunc() : function()
    {
        alert(this.personName);
    }, 
    createShape() : function()
    {
        this.personShape = paper.rect(40,40,40,40).attr({"fill":"blue"});
        $(this.personShape.node).click(function()
        {

            alert(this.personName);
        });
    }
});

The alert doesn't work for the click event and I do understand its because it cannot access the object variable 'personName'. I would however like to know whether or not it is possible to access it in some way?

Would there be a neat little Javascript trick to achieve this?


Inside your click function in createShape, the context is being set to this.personShape.node. this no longer refers to your person so it needs to be cached. Try this:

createShape: function() {
    var context = this;
    context.personShape = paper.rect(40,40,40,40).attr({"fill":"blue"});
    $(context.personShape.node).click(function() {
        alert(context.personName);
    });
}

Also, your functions shouldn't have parenthesis in your Class/object definition. Also, it's a good idea to start putting your curly braces on the same line as your statement for a few reasons. Here's my refactor:

var person = new Class({
    initialize: function(name) {
        this.personName = name;
        alert(this.personName)        //WORKS :-)

        this.testFunc();              //WORKS :-)
        this.createShape();
    },
    testFunc: function() {
        alert(this.personName);
    }, 
    createShape: function() {
        var context = this;
        context.personShape = paper.rect(40,40,40,40).attr({"fill":"blue"});
        $(context.personShape.node).click(function() {
            alert(context.personName);
        });
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜