我有一个父 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/