Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/backbone.js/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 在子视图中获取主干父视图事件_Javascript_Backbone.js_Delegates_Bind - Fatal编程技术网

Javascript 在子视图中获取主干父视图事件

Javascript 在子视图中获取主干父视图事件,javascript,backbone.js,delegates,bind,Javascript,Backbone.js,Delegates,Bind,我有一个父视图,在父html中我呈现一个子视图 看法单击放置的按钮可重复子视图 在父html中。但是我没有得到按钮点击事件里面 子视图事件,因为按钮html位于父html中。如何在子视图中获取单击事件 JS: HTML: <script type="text/template" id='par'> <div id='par'> <div id='repeatable-child-sectn'></div> <div id=

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

JS:

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>

添加子项
子部分

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

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

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:

您的方法是错误的。“添加子项”应该是父项的功能,而不是子项的功能。此外,多个视图实例不应指向同一元素此答案很好,除了使用
$(“#repeatable child sectn”)
。。。理想情况下,不应该有全局选择器。子视图也可以自渲染。。。
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;
  }
});