我知道函数listenTo,并且我需要在困难条件下应用它。我有一个数组,数组中的每个条目都是对集合的引用。我需要等待所有集合都已完全获取。我的获取函数集合通过重置函数存储数据。我监听事件重置。
var postTwitter= new Array();
var postInstagram= new Array();
var i=0;
_.each(AttoriCollectionDb.models, function (model) {
postTwitter[i]=new Posts();
postTwitter[i].fetch({'user_id':model.get("id_twitter"),'type':'twitter'});
postInstagram[i]=new Posts();
postInstagram[i].fetch({'user_id':model.get("id_instagram"),'type':'instagram'});
i++;
});
this.listenTo(postTwitter[0], 'reset', ok1);// now wait only one collection but I need wait all collection completely fetched.
在上面的代码中,我只等待单个集合重置,我如何监听所有集合何时将有重置事件?
最佳答案
这就是我的方法:
1) 添加自定义事件“reset:allPosts”,以便在所有帖子触发“reset”时触发
2) 收集您想要调用的“重置”触发器总数(所有帖子 instagram + twitter)。我将其命名为“totalPosts”
3) 设置范围变量“totalResetted”,以便您可以在帖子触发“重置”后增量添加
4) 每次“reset”触发后,向“totalResetted”添加 1 并检查“totalResetted”是否等于“totalPosts”。如果它相等,则意味着所有帖子都已触发“重置”
这是我的想法:
var postTwitter= new Array();
var postInstagram= new Array();
var totalPosts= AttoriCollectionDb.models.length * 2; // Times two because we're adding Twitter and Instagram
var totalResetted= 0;
var checkResetted = function() {
totalResetted++;
if (totalPosts === totalResetted) this.trigger('reset:allPosts');
}
// When all posts are 'reset' then do something;
this.on('reset:allPosts', function(){ alert('all posts fired reset!!') });
var i=0;
var that = this;
_.each(AttoriCollectionDb.models, function (model) {
postTwitter[i]=new Posts();
that.listenToOnce( postTwitter[i], 'reset', checkResetted);
postTwitter[i].fetch({'user_id':model.get("id_twitter"),'type':'twitter'});
postInstagram[i]=new Posts();
that.listenToOnce( postInstagram[i], 'reset', checkResetted);
postInstagram[i].fetch({'user_id':model.get("id_instagram"),'type':'instagram'});
i++;
});
关于javascript - 主干多监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23445920/