我正在使用Marionette 2.4,并且有一个layoutView正在监听childView中的事件。事件触发时,我在集合中搜索现有模型,如果不存在,则创建一个新模型并将其添加到集合中。如果找到该模型,则从集合中删除该模型。问题在于该事件似乎触发了两次。第一次触发时,它将创建模型,但是在触发两次时,它将在集合中找到新创建的模型,然后将其删除。
var layout = Marionette.LayoutView.extend({
childEvents: {
'channel:selected': 'onChildviewChannelSelected'
},
onChildviewChannelSelected: function (childView, args) {
var linkCollection = this.getRegion('regionWithCollectionView').currentView.collection;
var modelToUpdate = linkCollection.where({channel: args.currentTarget.value});
if(modelToUpdate) {
this.removeModel(linkCollection, modelToUpdate);
} else {
this.addModel(linkCollection, args.currentTarget.value);
}
},
removeModel: function (collection, model) {
collection.remove(model);
},
addModel: function (collection, channel) {
var newEntity = new MyApp.Entities.Link();
newEntity.set('channel', channel);
collection.add(newEntity);
}
});
这是触发“ channel:selected”事件的子视图...。
var childView = Marionette.ItemView.extend({
events: {
'change input[type="checkbox"]': 'channelSelected'
},
channelSelected: function(args) {
this.triggerMethod('channel:selected', args);
}
});
知道为什么childView会触发两次'channel:selected'事件吗?
它不是持有要添加的集合的视图,但是当添加一个集合时,可能会发生某些事情,由于某种原因,它将再次触发该事件。
由于木偶的“ childview *事件冒泡”,您的函数似乎被触发了两次。从文档中:
当集合视图中的子视图触发事件时,该事件将在事件名称前带有“ childview:”的父集合视图中冒泡。
也就是说,如果子视图触发“ do:something”,则父集合视图将触发“ childview:do:something”。
这意味着该"childview:channel:selected"
布局已在您的layoutview上触发(这意味着该onChildviewChannelSelected
函数会在父视图上自动执行,如果它存在http://marionettejs.com/docs/v2.4.7/marionette.functions.html#marionettetriggermethod)。
似乎有一些潜在的解决方法。1-childEvents
如果您的处理程序/函数名称遵循木偶约定,则不要指定处理程序。
var LayoutView = Marionette.LayoutView.extend({
template: false,
el: '.container',
regions: {
'regionWithCollectionView': '.collection-view-container'
},
onChildviewChannelSelected: function (childView, args) {
console.log("layoutview::channelSelected - child " + childView.model.get('channel') + " selected");
}
});
小提琴显示解决方法#1:https : //jsfiddle.net/kjftf919/
2-将您的LayoutView的childview函数处理程序重命名为与Marionette的自动事件冒泡不冲突的名称。
var LayoutView = Marionette.LayoutView.extend({
template: false,
el: '.container',
regions: {
'regionWithCollectionView': '.collection-view-container'
},
childEvents: {
'channel:selected':'channelSelected'
},
channelSelected: function (childView, args) {
console.log("layoutview::channelSelected - child " + childView.model.get('channel') + " selected");
}
});
小提琴显示解决方法#2:https : //jsfiddle.net/kac0rw6j/
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句