I want to do the automatic initialization when dom was inserted, I know there are several ways, but is that passable to do it like event listening on jQuery
In the past, we can do something like
HTML
<button id="btn_add">add</button>
<div class="container"></div>
JS
$('#btn_add').on('click', function() {
var html = $('<div class="new"></div>');
$('.container').append(html);
});
$('.container').on('DOMNodeInserted', '.new', function() {
$(this).html('new content');
});
But DOMNodeInserted
was deprecated, We can do something like
$('#btn_add').on('click', function() {
var html = $('<div class="new"></div>');
$('.container').append(html).find('.new:last').trigger('created');
});
$('.container').on('created', '.new', function() {
$(this).html('new content');
});
or
$('#btn_add').on('click', function() {
var html = $('<div class="new"></div>');
$('.container').append(html);
doInit();
});
function doInit() {
$('.container').find('.new:last').html('new content');
}
But it's not as beautiful as listen DOMNodeInserted
, any better writing style?