骨干查看事件不发生,EL存在

时间:2014-01-20 19:54:48

标签: backbone.js

我经历过类似的讨论,仍然不知道为什么我的事件没有解雇。我似乎对骨干事件的运作方式缺乏一些基本的了解。

这是我的代码:

(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>

2 个答案:

答案 0 :(得分:1)

这是一个有效的解决方案http://jsfiddle.net/hcKv2/ 主要问题是您在.html()方法中使用.$el而不是骨干视图元素indicatorsView.render()

您需要在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;
}

有一个好的编码。

答案 1 :(得分:1)