问题:我正在通过JS模板系统创建一个元素。在该模板中,我指定了一个ID。在创建了ID之后,有没有办法用jQuery在创建特定元素时触发回调?
使用Knockoutjs的示例JS / HTML:
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());
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>
答案 0 :(得分:1)
您可以运行间隔来检查dom中的id,然后触发事件(如果存在)。
var intv = setInterval(function(){
var $el = $("#myId");
if ( $el.length > 0 ) {
clearInterval(intv);
doSomething();
}
}, 500);
如果从不显示,可能应该在事件发生10秒后清除间隔:
setTimeout(function(){
clearInterval(intv);
}, 10000);