我需要创建一个自定义事件,但只有在验证了两个条件时,在我的代码中,我才需要在完成两个add on collection时触发事件。最具体地说,只有在完成addInstagram和addTweets函数时才需要触发事件。
var Integrated = Backbone.Collection.extend({
model:IntegratedModel,
nextUrlInstagram:undefined,
InstagramQuery:undefined,
twitterQuery:undefined,
page: 0,
comparator:"dateString",
initialize: function () {
this.TweetsCollection = new Tweets();
this.InstagramCollection = new Instagrams();
this.listenTo(this.TweetsCollection,'reset',this.addTweets);
this.listenTo(this.InstagramCollection,'reset',this.addInstagram);
},
fetch: function() {
this.reset();
var self=this;
this.TweetsCollection.query=this.twitterQuery;
this.TweetsCollection.page=this.page;
this.TweetsCollection.fetch();
this.InstagramCollection.userId=this.InstagramQuery;
this.InstagramCollection.fetch();
},
addTweets: function(){//when this function and function below are completeed trigger event
console.log(this.TweetsCollection);
this.add(this.TweetsCollection.toJSON());
},
addInstagram: function(){
console.log(this.InstagramCollection);
this.add(this.InstagramCollection.toJSON());
},
});
return Integrated;
});
答案 0 :(得分:0)
为此,我创建了一个名为when
的方法。
因此,您可以放在fetch
方法的末尾:
this.when([this.TweetsCollection, this.InstagramCollection], 'sync', this.onBothLoaded);
你的when
会是这样的:
when: function (models, eventName, callback) {
callback = _.after(models.length, callback);
for (var i = 0, l = models.length; i < l; i++)
this.listenToOnce(models[i], eventName, callback);
}
这应该有用。
希望我帮助过。