2014-01-20 39 views
0

我已經經歷了類似的討論,仍然不知道爲什麼我的事件沒有被解僱。我似乎缺乏對骨幹事件如何工作的基本理解。骨幹觀看事件不燒,EL存在

這裏是我的代碼:

(function() { 

    MP.IndicatorView = Backbone.View.extend({ 
    template: JST['backbone/templates/indicator'], 
    className: 'row indicator', 

    initialize: function() { 
     console.log(this); 
     console.log(this.el); 
     _.bindAll(this, 'collapse'); 
    }, 

    events: { 
     "click .control" : "collapse" 
    }, 

    collapse: function (e) { 
     console.log('shit'); 
     var $el = $(e.target); 

     $el.toggleClass('expand'); 

     var $panelToPoke = $el. 
     parents('.top-container'). 
     siblings('.bottom-container') 
     , $parentPanel = $panelToPoke.parents('.indicator') 
     , isVisible = $panelToPoke.is(':visible'); 

     $parentPanel.toggleClass('expanded'); 

     isVisible ? $panelToPoke.slideUp() : $panelToPoke.slideDown(); 
    }, 

    render: function() { 
     // Don't show offers that have no transactions 
     if (this.model.get('transactionCount') > 0) { 
     this.$el.html(this.template(this.model.for_template())); 
     } 
     return this.$el; 
    } 
    }); 

    MP.IndicatorsView = Backbone.View.extend({ 
    el: '#indicators', 

    render: function() { 
     var view; 
     var subViews = this.collection.reduce(function (memo, indicator) { 
     view = new MP.IndicatorView({ model: indicator }); 
     memo += view.render().html(); 
     return memo 
     }, ''); 

     this.$el.html(subViews); 
     return this; 
    } 
    }); 
})(); 

如何看待被實例化:

var indicators = new MP.Indicators(coordinator.dump()); 
var indicatorsView = new MP.IndicatorsView({ collection: indicators }); 
indicatorsView.render(); 

模板:

瀏覽:

<div class="row indicator"> 

    <div class='top-container'> 
    <ul class="inline-list mainpanel"> 
     <li> 
     <div class='control expand'></div></li> 
     <li class="state <%= is_active ? 'active' : 'expired' %>"></li> 

回答

1

這裏是一個可行的解決方案http://jsfiddle.net/hcKv2/ 主要問題是您在indicatorsView.render()方法中使用.html()而不是主幹視圖元素.$el

您需要在render方法內部返回this才能實現鏈模式,但是如果您在子視圖中返回$el,則不一定需要。

render: function() { 
    var view; 
    var subViews = this.collection.reduce(function (memo, indicator) { 
    view = new MP.IndicatorView({ model: indicator }); 
    //memo += view.render().html(); 
    this.$el.append(view.render()); 
    // or this.$el.append(view.render().$el); 
    // if you return this inside render method 
    return memo 
    }, ''); 

    //this.$el.html(subViews); 
    return this; 
} 

有一個很好的編碼。

+0

是因爲HTML()是無法訪問的當視圖渲染()? –

+0

哦,我看到...如果我使用HTML(),我沒有綁定$ el元素到集合視圖$ el ..非常感謝,尤金!!!! –