【问题标题】:Getting Backbone parent view events inside child view在子视图中获取主干父视图事件
【发布时间】:2016-07-05 15:18:47
【问题描述】:

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

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>

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

【问题讨论】:

  • 你的方法是错误的。 “添加孩子”应该是父母的功能,而不是孩子的功能。多个视图实例也不应该指向同一个元素

标签: javascript backbone.js delegates bind


【解决方案1】:

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

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/

【讨论】:

  • 这个答案很好,除了使用$('#repeatable-child-sectn')... 理想情况下不应该有一个全局选择器。子视图也可以自行渲染...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多