2014-12-09 75 views
0

通過Ajax創建新用戶時,新的用戶元素(該元素是手動創建的)未被委派事件。在Backbone中新創建的元素未被委派偵聽器

如果我嘗試將我的元素從一個列表移動到另一個列表,則會調用this.delegateEvents()點擊偵聽器。但是,無論我嘗試什麼,我都無法讓點擊偵聽器應用到這個新創建的元素。

事件甚至不需要附加到模型上,只需要一個簡單的顯示/隱藏事件即可。

events: { 
     'click a.toggle': 'toggleContent', 
    }, 

addNewUserElement: function (userId) { 
    var $formName = this.$('form').attr('name'); 
    var $listElement = this.createNewListElement(userId, $formName); 
    this.trigger('user-created-event', $listElement); // this.onUserCreate 
}, 

createNewListElement: function (userId, $formName){ 
    var html = this.$('form input#' + $formName + '_lastName').val().toUpperCase() 
    // more html creation 
    return html; 
} 

onUserCreate: function ($el) { 
    var targetList = '#active-users' 
    alert("User created"); 
    this.insertIntoList(targetList, $el); 
}, 

insertIntoList: function(targetList, $elementToMove){ 
     this.undelegateEvents(); 
     var added = false; 
     var $targetList = // grab a set of <li>'s 

     $targetList.append($elementToMove); 

     this.delegateEvents(); 
     return false; 
    }, 
+0

你能提供一個簡化的,最好是自包含的例子嗎?這裏有很多噪音,你需要刪除,你不能指望人們通過所有這些,也許在jsfiddle.net上的功能演示會有所幫助。 – 2014-12-09 18:06:21

+0

'createTargetListHandle'做了什麼? – 2014-12-10 10:39:01

+0

@UziKilon哦對不起,我正在清理代碼,它只是返回一些更多的HTML它不太相關 – JackalopeZero 2014-12-10 10:39:44

回答

0

我在這裏遇到的問題是我創建了一個原始的HTML片段而沒有將其附加到Backbone模型。它需要附加到JS模型並手動分配所有相關的偵聽器。這也是爲什麼從一個列表移動元素到另一個列表不會產生相同的問題,因爲他們已經附加到其他JS類。

在代碼的另一部分,有一個createChildViews方法,所以我分離出來,並通過這種方法通過了新的HTML的一部分:

createChildViews: function() { 
    var $els = this.$('#active-users li, #deactivated-users li'); 
    _.each($els, function (element) { 
     this.createChildView(element); 
    }, this); 
}, 

createChildView: function(element){ 
    var user = new User({ // the other JS class 
     el: element 
    }); 
    this.listenTo(user, 'user-created-event', function (view) { 
     this.onUserCreate(view); 
    }, this); 

}, 

onUserCreate: function ($el) { 
    var targetList = '#active-users'; 
    window.alert("User created"); 
    this.createChildView($el); 
    this.insertIntoList(targetList, $el); 
}, 

這意味着所有相關的偵聽器附着到HTML。

相關問題