views:

29

answers:

1

I ran into an interesting issue today. I have canvas elements that I am storing in a 'template'. I clone this template then append it to my document.

This works fine, except that I need to draw the canvas manually after they have been appended to the DOM, if I do this in the template they are no longer cloneable and jQuery seems to lose the ability to clone them.

I am unaware of any specific ready events for this sort of case.

Example code:

var template = $("<canvas></canvas");

var clone = template.clone();
var canvas = $("canvas",clone)[0];
var context = canvas.getContext("2d");
context.beginPath()
context.moveTo(center[0],center[1]);
context.arc( 50, 50, 25, 0, Math.PI, false );
context.lineTo( 25, 25 );
context.closePath();
context.fillStyle = "blue";
context.fill();

Note, I provided this code as a sample, this is not what I am using in my application. I can draw canvases just fine, so if this code is broken, sorry.


EDIT: posting addition to question from OP's comment

okay...

var template = $("<context>"); 
clone = template.clone(); 
$("body").append(clone); 
function cloneready(){ alert('clone exists); }; 

There you go, make cloneready execute when clone has been appended. I think I will go a different route and use canvas deep copy to make this work.

A: 

If you want to trigger code on DOM modification, there's no native cross-browser event for this.

There is however a plugin called livequery that can do this (when you make DOM modifications using jQuery methods).

It would look something like:

$('canvas').livequery(function() { 
    alert('clone exists'); 
});

Or, of course if you already have a named function, like this:

function cloneready(){ alert('clone exists'); };

$('canvas').livequery( cloneready );

It can also accept a second function argument that will fire when an item matching the selector is removed from the DOM.

Additionally, methods like .addClass() will trigger a livequery selector if you add a class to match the selector given:

$('.someClass').livequery( function() {
    alert('new someClass');
});

$('div').addClass('someClass'); // The livequery code will fire
patrick dw