Problem: I am creating an element via a JS templating system. Inside that template I am specifying an ID. After that ID is created, Is there a way with jQuery to fire a callback when a specific element is created?
Example JS/HTML with Knockoutjs:
function Dialogs(){
this.createDialog = function(id){
//alert('creating dialog');
// If i add a setTimeout here, it will work.
$("#" + id).dialog({
autoOpen: true,
resizable: false,
width: 360,
height: 200,
dialogClass: 'systemError',
modal: true,
closeText: 'hide'
});
};
this.data = ko.observableArray([
new Dialog("Demo", 'htmlContent', {
id: 'testDialog',
success: function() {},
error: function(){},
actions:[
new DialogAction('continue', {
className: 'foo',
id: 'bar',
events: {
click: function() {
console.log('do stuff');
}
}
})
]
})
]);
}
function Dialog (name, htmlContent, options) {
options = options || {};
this.id = options['id'] || '';
this.name = ko.observable(name || "");
this.className = options['className'] || '';
this.htmlContent = ko.observable( htmlContent || "");
this.successCallback = options['success'] || this.close;
this.errorCallback = options['error'] || this.throwError
this.actions = options['actions'] || [];
}
function DialogAction (name, options) {
options = options || {};
this.name = ko.observable(name || "");
this.className = options['className'] || null;
this.id = options['id'] || null;
this.successCallback = options['success'] || null;
this.errorCallback= options['error'] || null;
}
ko.applyBindings(new Dialogs());
The HTML:
<div id="dialog-holder" data-bind="foreach: Dialogs.data()">
<div class="systemErrorDialog" data-bind="template: { name: 'dialog-system-error', data: $data, afterRender: Global.Dialogs.createDialog($data.id) }"></div>
</div>
<script type="text/template" id="dialog-system-error">
<div data-bind="html:htmlContent(), attr:{id: id, class:className,title:name()}">
<div class="actions" data-bind="foreach: actions">
<div data-bind="attr:{id: name(), class: className}"></div>
</div>
</div>
</script>