2012-11-09 45 views
1

我有這樣的階段相關聯的容器:獲取階段從容器中kineticjs

HTML:

<div id="container"> 

腳本1:

var stageInFirstScript = new Kinetic.Stage({ 
    container: document.getElementById('container'), 
    width: this.SKETCH_WIDTH, 
    height: this.SKETCH_HEIGTH 
}); 

在第二個劇本,我需要操縱剛剛創建的舞臺上的形狀。是否有可能用這樣的東西檢索stageInFirstScript?

腳本2:

var stageInSecondScript = document.getElementById('container').RetrieveExistingStage(); 
//now I have retrieved stageInFirstScript 
//I can add shapes to it, etc.... 

任何幫助或替代解決方案將不勝感激!

回答

2

您應該能夠簡單地引用您創建的變量,即「stageInFirstScript」。但是,如果這兩個腳本是兩個獨立的範圍內,儘量使這個變量全局,然後訪問它像一個,像這樣(我將使用jQuery的這個例子):

Script1.js:

var stageInFirstScript; // declaring global variable 

$(window).load(function() { 

    // assigning new stage to the global variable 

    stageInFirstScript = new Kinetic.Stage({ 
     container: document.getElementById('container'), 
     width: this.SKETCH_WIDTH, 
     height: this.SKETCH_HEIGTH 
    }); 

}); 

然後在script2.js:

function doSomething() { 

    // accessing global variable and calling its method 

    stageInFirstScript.setHeight(300); 

} 

這應該在窗口加載後,只要變量已被定義後調用函數時,工作在這種情況下。

如果您想要獲取任何容器的舞臺,我可以考慮的一種方法是創建一個將動力學階段與容器(或其ID)相關聯的數組。

+0

愚蠢,因爲它聽起來,來自java我已經忘記了全局變量。看起來很奇怪,讓這些glob var漂浮在類或函數之外。多謝。 – seinecle