2015-10-18 69 views
0

我在PaperScript中创建了两类对象:Node s和Line s。每行都有一个this.nodes属性,该属性是引用两个节点对象的数组,每行一个。节点具有this.dragging属性,当创建节点对象时,该属性被初始化为false,但在onMouseDown事件上被设置为true,并且被设置回falseonMouseUp。这样我就可以跟踪节点是否意图在某个时间点移动。尝试从另一个对象访问对象属性始终返回属性的初始值

现在我希望能够从Line对象中检查其关联节点是否在任何时间点被拖动。为此我有一个if语句来检查是否(this.nodes[0].dragging == true || this.nodes[1].dragging == true)。如果这返回true,则可能会发生进一步的操作。

问题是无论我是否拖动节点,两个this.nodes[i].dragging都始终返回false。为什么会发生?特别是当我从Node对象中检查this.dragging的值时,它确实会在拖动时返回正确的true值,否则返回false。

编辑包括一些代码:

以下是我的代码的精简版。重要的是this.dragging变量。

function Node(pos) { 

///// Stuff 

    this.dragging = false; 
    this.node.onMouseDown = function(event) { 
    this.dragging = true; 
    // Do other stuff 
    } 
    this.node.onMouseDrag = function(event) { 
    if (this.dragging == true) { 
     // Do stuff 
    } 
    } 
    this.node.onMouseUp = function(event) { 
    // Do stuff 
    this.dragging = false; 
    } 
} 

以下是(的一部分)的构造函数Line对象:

function Line(p1, p2) { 
    this.nodes = [p1, p2]; 

    ///// Stuff 

    this.update = function() { 
    if (this.nodes[0].dragging === true || this.nodes[1].dragging === true) { 
     // True 
    } else { 
     // False 
    } 
    } 
} 

2日编辑评论者要求我如何实例化这些对象:

我实例化它们如下:

var nodeNum = 7; 
var lineConnections = [{ 
    from: 0,to: 1} 
    ,{from: 0,to: 2} 
    ,{from: 0,to: 3} 
    ,{from: 0,to: 4} 
    ,{from: 1,to: 2} 
    ,{from: 1,to: 5} 
    ,{from: 2,to: 3} 
    ,{from: 2,to: 4} 
    ,{from: 3,to: 5} 
    ,{from: 4,to: 5} 
    ,{from: 2,to: 5} 
] 

function init() { 
    for (var i = 0; i < nodeNum; i++) { 
    Nodes[i] = new Node(); 
    } 

    for (var i = 0; i < lineConnections.length; i++) { 
    Lines[i] = new Line(Nodes[lineConnections[i].from], Nodes[lineConnections[i].to]); 
    } 
} 

init(); 

现场演示可在http://aronadler.com/experiment/

+0

首先,体面的探索,但我们不能开始猜测没有一些代码。请发布您的类构造函数等。如果它更复杂,JFiddle会很好的工作。 – Wobbles

+0

最初的想法,我可能会使用===运算符进行测试,因为== true有时可能表现错误,具体取决于属性的解释方式。 – Wobbles

+0

我无法弄清楚如何让我的PaperScript文件的内容在JSFiddle中工作,所以如果我将它链接到托管的域名就足够了。该项目目前在http://aronadler.com/experiment/ – Aron

回答

1

我认为问题是this,如下代码中的this.dragging指的是全局对象(窗口),而不是你创建的对象。

this.node.onMouseDown = function(event) { this.dragging = true; // Do other stuff } this.node.onMouseDrag = function(event) { if (this.dragging == true) { // Do stuff } } this.node.onMouseUp = function(event) { // Do stuff this.dragging = false; }

您可以通过,如果全局变量拖动已创建看到检查。我不能真正修改你的代码,除非它在小提琴或其他易于使用的位置,但是你应该可以通过将每个鼠标处理函数绑定到此处来修复它,如下所示: this.node.onMouseUp = function(event) { // Do stuff this.dragging = false; }.bind(this) 或创建与本地参考封闭此不会改变,如在:

self = this;

然后从相对于this功能内指self

+0

实际上,这在纸张Tool事件的上下文中是指工具对象,而不是窗口。 – bmacnaughton

相关问题