我有幾個模塊:「Shapes.js」,它是Shape對象的容器(模塊「Shape.js」)「Mouse.js」,它將在用戶按鼠標左鍵單擊鼠標時計算座標以及需要進行計算並確定該座標屬於該形狀的模塊「Selection.js」。Require.js,模塊依賴關係
// Mouse.js
define([], function() {
function Mouse(element, e) {
var offsetX = 0, offsetY = 0;
if (element.offsetParent !== undefined) {
do {
offsetX += element.offsetLeft;
offsetY += element.offsetTop;
} while ((element = element.offsetParent));
}
this.getMouseX = function() {
return e.pageX - offsetX;
}
this.getMouseY = function() {
return e.pageY - offsetY;
}
}
return Mouse;
});
// Selection.js
define(['modules/Shapes', 'modules/Mouse'], function(Shapes, Mouse) {
var selection;
document.getElementById('canvas').addEventListener('mousedown', function(e) {
selection = null;
var mouse = new Mouse(document.getElementById('canvas'), e);
var shapes = Shapes.getShapes();
for(var i=0; i<shapes.length; i++) {
if ((shapes[i].getX() <= mouse.getMouseX())
&& (shapes[i].getX() + shapes[i].getWidth() >= mouse.getMouseX())
&& (shapes[i].getY() <= mouse.getMouseY())
&& (shapes[i].getY() + shapes[i].getHeight() >= mouse.getMouseY())) {
selection = shapes[i];
break;
}
}
});
return selection;
});
爲了使這個問題小我不會發表 「形狀」 和 「形狀」 模塊,他們不重要。
因此,現在在「main.js」模塊中,我希望在用戶triger mousedown事件時始終引用所選元素(或null),但我無法獲取它。甚至不知道從哪裏開始。如果我只是加載主模塊中的選擇模塊,我將永遠得到undefined.Thanks提前。
(代碼片段是從西蒙·薩里斯帆布教程,稍作修改,只是想通過Require.js做的一切)
編輯:@ Katana314,你認爲這樣的事情?
// Selection.js(編者)
define(['modules/Shapes', 'modules/Mouse'], function(Shapes, Mouse) {
var selection;
return function(e) {
selection = null;
var mouse = new Mouse(document.getElementById('canvas'), e);
var shapes = Shapes.getShapes();
for(var i=0; i<shapes.length; i++) {
if ((shapes[i].getX() <= mouse.getMouseX())
&& (shapes[i].getX() + shapes[i].getWidth() >= mouse.getMouseX())
&& (shapes[i].getY() <= mouse.getMouseY())
&& (shapes[i].getY() + shapes[i].getHeight() >= mouse.getMouseY())) {
selection = shapes[i];
break;
}
}
return selection;
}
});
// Main.js
document.getElementById('canvas').addEventListener('mousedown', function(e) {
console.log(Selection(e)); // Shape... :D
});
我必須承認,我不完全理解你的解釋,你能更具體嗎? – Srle
順便說一下,我不想從Selection中返回構造函數。JS,因爲目前只有一個選擇可以存在。 – Srle