Search code examples
javascriptbackbone.jsdelegatesbind

Getting Backbone parent view events inside child view


I have a parent view and inside the parent html I am rendering a child view. Child view is repeatable on click of a button which is placed inside parent html. But I am not getting the button click event inside the child view events as the button html is inside parent html. How can I get the click event inside the child view?

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>

Can we get the parent events inside child view?


Solution

  • I would take a slightly different approach and simplify things by having the parent view listen for the 'add child' button clicks, as well as manage instantiating and appending children views:

    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/