Raphael中的委托拖动功能

Delegating drag function in Raphael

本文关键字:拖动 功能 Raphael      更新时间:2023-09-26

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

我是javascript的新手,所以我可能犯了一个非常明显的错误,但我没有发现。我在委派函数moveTextdragTextupText中是否滥用了call()?或者这是拉斐尔的作品?如有任何帮助,我们将不胜感激。

<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>

解决方案

正如这个答案所指出的,问题产生于属性名称的选择:

// 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);
}
// Associate the shape and text elements with each other
shape.text = text;
text.shape = shape;

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