Associate PaperScope objects with the script tag that produced them through an assigned unique id.

This commit is contained in:
Jürg Lehni 2011-05-16 00:29:29 +01:00
parent 78a9f9afe9
commit 593813660a
3 changed files with 26 additions and 12 deletions

View file

@ -24,6 +24,7 @@ var PaperScope = this.PaperScope = Base.extend({
this.documents = [];
this.tools = [];
this.id = id;
PaperScope.scopes[id] = this;
},
/**
@ -41,15 +42,19 @@ var PaperScope = this.PaperScope = Base.extend({
}, scope);
},
// Methods for setting and restoring paper scopes:
statics: {
set: function(scope) {
this.previous = paper;
paper = scope;
},
remove: function() {
// Remove all documents and tools.
for (var i = this.documents.length - 1; i >= 0; i--)
this.documents[i].remove();
for (var i = this.tools.length - 1; i >= 0; i--)
this.tools[i].remove();
},
restore: function() {
paper = this.previous;
statics: {
scopes: {},
get: function(id) {
return this.scopes[id] || null;
}
}
});

View file

@ -195,7 +195,8 @@ var PaperScript = this.PaperScript = new function() {
}
function load() {
var scripts = document.getElementsByTagName('script');
var scripts = document.getElementsByTagName('script'),
count = 0;
for (var i = 0, l = scripts.length; i < l; i++) {
var script = scripts[i];
// Only load this script if it not loaded already.
@ -204,13 +205,22 @@ var PaperScript = this.PaperScript = new function() {
// Produce a new PaperScope for this script now. Scopes are
// cheap so let's not worry about the initial one that was
// already created.
var scope = new PaperScope(script.src || ('script-' + i));
// Define an id for each paperscript, so its scope can be
// retrieved through PaperScope.get().
var scope = new PaperScope(script.getAttribute('id')
|| script.src || ('paperscript-' + (count++)));
// Make sure the tag also has this id now. If it already had an
// id, we're not changing it, since it's the first option we're
// trying to get an id from above.
script.setAttribute('id', scope.id);
// If a canvas id is provided, create a document for it now,
// so the active document is defined.
var canvas = script.getAttribute('canvas');
if (canvas = canvas && document.getElementById(canvas)) {
// Create a Document for this canvas, using the right scope
paper = scope;
// XXX: Do not pass canvas to Document.
// Create DocumentView here instead.
new Document(canvas);
}
if (script.src) {

View file

@ -78,8 +78,7 @@ var Document = this.Document = Base.extend({
remove: function() {
var res = Base.splice(this._scope.documents, null, this._index, 1);
this._scope = null;
// Remove all views. This also removes the event handlers installed for
// then.
// Remove all views. This also removes the installed event handlers.
for (var i = this.views.length - 1; i >= 0; i--)
this.views[i].remove();
return !!res.length;