Backbone.js 等待主干模板附加到dom
我试图将事件绑定到通过附加主干模板放置的元素:Backbone.js 等待主干模板附加到dom,backbone.js,asynchronous,Backbone.js,Asynchronous,我试图将事件绑定到通过附加主干模板放置的元素: appendEditTemplateAndSetEvents: function() { var associatedCollection = App.Helpers.findAssociatedCollection(this.allCollections, this.associatedCollectionId); var template = this.setEditTempla
appendEditTemplateAndSetEvents: function() {
var associatedCollection = App.Helpers.findAssociatedCollection(this.allCollections, this.associatedCollectionId);
var template = this.setEditTemplateForElement(associatedCollection.type);
var modalBody = this.$el.find('.modal-body');
modalBody.empty();
var firstModel = associatedCollection.at(0);
if(template.mainTemplate !== null) {
modalBody.append($('#edit-form-element-frame').html());
//each mode in collection
associatedCollection.each(function(model){
if(model.get('positionInContainer') === 1) {
firstModel = model;
}
console.log(model.attributes);
modalBody.find('.elements-in-editmodal-wrapper').append(template.mainTemplate(model.toJSON()));
});
}
if( template.templateValidation.length !== 0 ) {
modalBody.append('<hr><h3>Validateregels</h3>');
_.each(template.templateValidation, function(val, index) {
modalBody.append(val(firstModel.toJSON()));
});
}
//set listeners and handlers that apply when a edit modal is open
this.validationEventsForEditModal(firstModel);
this.editErrorMessagesInModal(firstModel);
},
appendEditTemplateAndSetEvents:function(){
var associatedCollection=App.Helpers.findAssociatedCollection(this.allCollections,this.associatedCollectionId);
var template=this.setEditTemplateForElement(associatedCollection.type);
var modalBody=this.$el.find('.modalBody');
modalBody.empty();
var firstModel=associatedCollection.at(0);
如果(template.mainTemplate!==null){
modalBody.append($('#edit form element frame').html());
//集合中的每个模式
关联集合。每个(函数(模型){
if(model.get('positionInContainer')==1){
firstModel=模型;
}
console.log(model.attributes);
modalBody.find('.elements in editmodel wrapper').append(template.mainTemplate(model.toJSON());
});
}
if(template.templateValidation.length!==0){
append(“
Validateregels”);
_.each(template.templateValidation,函数(val,索引){
append(val(firstModel.toJSON());
});
}
//设置打开编辑模式时应用的侦听器和处理程序
这个.validationEventsForEditModal(firstModel);
此.editErrorMessagesInModal(firstModel);
},
现在的问题是,当调用最后两个函数时,模板的html尚未追加,因此事件绑定到长度为0的对象
有没有人能为这个异步问题找到合适的解决方案?我尝试了$.Defferred,但不起作用,但可能有人让它起作用。我通过在函数中使用
this.$el.find(…)
解决了这个问题:
this.validationEventsForEditModal(firstModel);
this.editErrorMessagesInModal(firstModel);
我不知道这是否仍然是一个异步问题,但这解决了它