在Raphael中委派拖动功能

时间:2012-01-12 04:57:39

标签: javascript raphael

使用Raphael,我希望能够拖动包含文本对象的形状(下例中的椭圆),拖动形状或文本。我希望通过将传递给text元素的drag()方法的函数设置为委托给相关的形状(尝试更加多态的this other one方法)来实现这一点。但是,当调用text.drag(...)时,这会导致错误“ obj.addEventListener不是函数”。

我是javascript的新手,所以我可能犯了一个非常明显的错误,但我无法发现它。我是否在代理功能call()moveTextdragText中误用了upText?或者这是拉斐尔的事吗?任何帮助将不胜感激。

<html>
<head>
<title>Raphael delegated drag test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="js/raphael.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript">
window.onload = function initPage() {
    'use strict';
    var paper = Raphael("holder", 640, 480);
    var shape = paper.ellipse(190,100,30, 20).attr({
            fill: "green", 
            stroke: "green", 
            "fill-opacity": 0, 
            "stroke-width": 2, 
            cursor: "move"
        });
    var text = paper.text(190,100,"Ellipse").attr({
            fill: "green", 
            stroke: "none", 
            cursor: "move"
        });

    // Associate the shape and text elements with each other
    shape.text = text;
    text.shape = shape;

    // Drag start
    var dragShape = function () {
        this.ox = this.attr("cx");
        this.oy = this.attr("cy");
    } 
    var dragText = function () {
        dragShape.call(this.shape);
    }

    // Drag move
    var moveShape = function (dx, dy) {
        this.attr({cx: this.ox + dx, cy: this.oy + dy});
        this.text.attr({x: this.ox + dx, y: this.oy + dy});
    }
    var moveText = function (dx,dy) {
        moveShape.call(this.shape,dx,dy);
    }

    // Drag release
    var upShape = function () {
    }       
    var upText = function () {
        upShape.call(this.shape);
    }

    shape.drag(moveShape, dragShape, upShape);
    text.drag(moveText, dragText, upText);
};
</script> 
    <div id="holder"></div>
</body>
</html>

解决方案

正如this answer所指出的,问题源于选择属性名称:

// Associate the shape and text elements with each other
shape.text = text;
text.shape = shape;

将这些更改为更详细的名称(并且不太可能与Raphael冲突)会使问题消失,但将它们设置为data属性会更安全:

// Associate the shape and text elements with each other
shape.data("enclosedText",text);
text.data("parentShape",shape);

// Drag start
var dragShape = function () {
    this.ox = this.attr("cx");
    this.oy = this.attr("cy");
} 
var dragText = function () {
    dragShape.call(this.data("parentShape"));
}

// Drag move
var moveShape = function (dx, dy) {
    this.attr({cx: this.ox + dx, cy: this.oy + dy});
    this.data("enclosedText").attr({x: this.ox + dx, y: this.oy + dy});
}
var moveText = function (dx,dy) {
    moveShape.call(this.data("parentShape"),dx,dy);
}

1 个答案:

答案 0 :(得分:3)

// Associate the shape and text elements with each other
shape.text = text;
text.shape = shape;

您正在向Raphael对象添加属性。在不知道拉斐尔如何工作(或将来会工作)的情况下,这很危险,显然也是造成问题的原因。如果您真的想要关联它们,我建议您使用Raphaels Element.datahttp://raphaeljs.com/reference.html#Element.data