开发者

DOM ready callback

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 usi开发者_如何学Cng 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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜