骨干视图事件不发射,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>

这是一个工作解决方案http://jsfiddle.net/hckv2/主要的问题是您被使用.html()而不是骨干视图元素.$el indicatorsView.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;
}

有一个很好的编码。

furthur的一些引用解释原因:

http://ianstormtaylor.com/rendering-views-in-backbonejs-isnt-always-always-simple/

最新更新