是否可以使用Backbone.View.events
定义来侦听自定义子视图事件?
儿童定义
缓存所有click
个事件并触发我的clicked
功能:
var Child = Backbone.View.extend({
events : {
'click' : 'clicked'
},
clicked: function() {
alert('View was clicked');
this.trigger("customEvent");
},
render: function() {
this.$el.html("<span>Click me</span>");
}
});
家长定义
为什么customEvent
个事件不会调用我的action
函数?
var Parent = Backbone.View.extend({
events : {
'customEvent' : 'action'
},
action : function() {
alert('My sub view triggered a custom event');
},
render : function() {
var child = new Child();
this.$el.append(child.el);
child.render();
}
});
创建并渲染父
var parent = new Parent();
parent.$el.appendTo(document.body);
parent.render();
我知道可以使用listenTo
代替,但使用事件定义似乎更清晰。
我的目的是建立一个子视图(例如颜色选择器),它在事件完成后触发事件。
答案 0 :(得分:9)
快速注释: -
如果您只想使用自定义事件,可以在此处查看Your Updated Fiddle
var Child = Backbone.View.extend({
initialize: function(options) {
this.parent = options.parent;
},
events : {
'click' : 'clicked'
},
clicked: function() {
alert('View was clicked');
this.parent.trigger("customEvent");
},
render: function() {
this.$el.html("<span>Click me</span>");
}
});
var Parent = Backbone.View.extend({
initialize: function() {
this.on('customEvent', this.action);
},
action : function() {
alert('My sub view triggered a custom event');
},
render : function() {
var child = new Child({parent: this});
this.$el.append(child.el);
child.render();
}
});
var parent = new Parent();
parent.$el.appendTo(document.body);
parent.render();