2013-11-25 23 views
1

我有以下ItemView其被包裝在裏面CollectionView如何手動調用ItemView函數?

define(deps, function($, _, Backbone, CountriesTemplate, Globals) { 
    return Backbone.Marionette.CollectionView.extend({ 
    tagName: 'ul', 
    className: 'unstyled countries', 
    itemView: Backbone.Marionette.ItemView.extend({ 

     tagName: 'li', 
     template: CountriesTemplate, 

     events: { 
     'change': 'toggleState' 
     }, 

     triggers: { 
     'click': 'toggleState' 
     }, 

     toggleState: function() { 
     var index = Globals.defaultCountries.indexOf(this.model.id); 
     index === -1 ? Globals.defaultCountries.push(this.model.id) : Globals.defaultCountries.splice(index, 1); 
     this.model.set('checked', !this.model.get('checked')); 
     } 
    }) 
    }); 
}); 

集合被結合到複選框列表和它被手動綁定到SVG圈元件,其代表的國家。檢查/取消選中複選框不成問題,並且應該調用toggleState。當嘗試手動觸發事件時單擊一個svg圈元素時出現問題。

試圖手動觸發點擊事件代碼:

// country is a "model" 
checkbox.prop('checked', true); 
// Changes the checked attribute but does not call toggleState.   
country.set('checked', true); 
// Nothing happens here. 
country.trigger('click'); 

那麼,什麼是手動調用toggleState正確的方法是什麼?

更新:

使用damienc88的答案,我做內部itemView以下修改,使觸發器工作。

itemView: Backbone.Marionette.ItemView.extend({ 
    tagName: 'li', 
    template: CountriesTemplate, 

    events: { 
    'change': 'toggleState' 
    }, 

    initialize: function() { 
    this.listenTo(this.model, 'toggleState', this.toggleState); 
    }, 

    toggleState: function() { 
    // Code. 
    } 
}) 

從外面打電話model.trigger('toggleState')現在工作,因爲它應該。

回答

1

如果您試圖直接在ItemView上調用toggleState,則可以調用itemView.toggleState();這隻有在您有權訪問該特定itemView對象時纔有效。你可能不知道。

或者,您也可以觸發模型中的事件,和ItemView控件可以監聽其模型中的事件:

this.listenTo(this.model,'toggleState',this.toggleState)。您的CollectionView則需要致電model.trigger('toggleState')

相關問題