在子视图中获取Backbone父视图事件

时间:2016-07-05 15:18:47

标签: javascript backbone.js delegates bind

我有一个父视图,在父html中我正在渲染一个孩子 视图。单击放置的按钮可以重复子视图 在父html中。但我没有得到里面的按钮点击事件 子视图事件,因为按钮html在父html中。如何在子视图中获取click事件?

JS:

var parView = Backbone.View.extend({ 
  template: _.template($('#par').html()),
  initialize: function(){
    this.render();
  },
   render: function () {
        this.$el.html(this.template);
        new childView({el:'#repeatable-child-sectn'});
        return this;
    }
});
var childView = Backbone.View.extend({ 
  template: _.template($('#child').html()),
  events: {
    'click #button': 'addChild'
  },
  initialize: function(){
    this.render();
  },
   render: function () {
        this.$el.html(this.template);
        return this;
    },
    addChild: function(){
      $('#repeatable-child-sectn').append(this.template);
    }
});

HTML:

<script type="text/template" id='par'>
  <div id='par'>
    <div id='repeatable-child-sectn'></div>
    <div id='button'>Add Child</div>
  </div>
</script>
<script type="text/template" id='child'>
  <div>Child Section</div>
</script>

我们可以在子视图中获取父事件吗?

1 个答案:

答案 0 :(得分:2)

我会采用略微不同的方法,通过让父视图监听“添加孩子”来简化事情。按钮点击,以及管理实例化和追加子视图:

var ParentView = Backbone.View.extend({
  template: _.template($('#par').html()),
  events: {
    'click #button': 'addChild'
  },
  initialize: function() {
    this.childViews = []; // keep track of childviews in case they need to be removed, etc.
  },
  render: function() {
    this.$el.html(this.template);
    return this;
  },
  addChild: function() {
    var childView = new ChildView();
    this.childViews.push(childView);
    this.$('#repeatable-child-sectn').append(childView.$el);
  }
});
var ChildView = Backbone.View.extend({
  template: _.template($('#child').html()),
  initialize: function() {
    this.render();
  },
  render: function() {
    this.$el.html(this.template);
    return this;
  }
});

JSFiddle:https://jsfiddle.net/9jms89n2/

相关问题