javascript - 在 subview 中获取 Backbone 父 View 事件

标签 javascript backbone.js delegates bind

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

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>

我们能否在 subview 中获取父事件?

最佳答案

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

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/

关于javascript - 在 subview 中获取 Backbone 父 View 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38207130/

相关文章:

ios - Sinch didReceiveIncomingCall 从未调用过

javascript - 导航栏下方的全屏 map

javascript - Set-Cookie 被阻止,因为它的 Domain 属性对于当前主机 url 无效

javascript - 如何检查 if/else 语句中的随机条件?

javascript - toJSON() 和 JSON.Stringify() 之间的区别

c# - 无法获取多播委托(delegate)中的第一个方法名称

javascript - 从表单选项获取 ID 并用它填充多个字段

javascript - 在 backbone.js 中从 DOM 初始化模型是否有意义?

javascript - 模型验证中的 Backbone JS : collection.plug()

iphone - 如何判断哪个控件被触摸了?