将一条消息从子视图发送到Backbone.js或Marionettejs中的父集合视图有什么好方法?
通常我通过集合发送消息:
INSERT INTO test01 (t1) VALUES ('')
我认为这是不对的,因为:
相反,我想直接从子视图向其父集合视图发送消息。 (实际上,我正在使用复合视图,不确定是否重要,但希望保持示例简单)。
答案 0 :(得分:4)
让子视图直接发出事件并让父视图监听它:
ChildView = Backbone.Marionette.ItemView.extend({
send_message: function(){
this.trigger('some-message');
}
})
ParentCollectionView = Backbone.Marionette.CollectionView.extend({
// ON RENDER
onRender: function(){
// no idea how Marionette references its children views
// let's say this.subview is a reference to your child view
this.listenTo(this.subview, 'some-message', this.do_something);
}
// DO SOMETHING
do_something: function(){
alert('did something');
}
});
或者使用您注入子视图的专用事件发射器
ChildView = Backbone.Marionette.ItemView.extend({
send_message: function(){
this.channel.trigger('some-message');
}
})
ParentCollectionView = Backbone.Marionette.CollectionView.extend({
initialize: function(){
this.channel = _.extend({}, Backbone.Events);
this.listenTo(this.channel, 'some-message', this.do_something);
},
// ON RENDER
onRender: function(){
// pass the channel to the child
// that probably should be done when the child is created
this.subview.channel = this.channel;
},
// DO SOMETHING
do_something: function(){
alert('did something');
}
});
答案 1 :(得分:1)
Marionette有一个名为triggerMethod的便捷函数,可以将事件从子节点发送到父节点。
this.triggerMethod("someMethod", data1...)
父级使用onChildview侦听器
捕获该事件onChildviewSomeMethod(childView, data1param, ...) {}