I'm using a Event Aggregator(EA) to keep track of all events in my app. But there is one situation I could not make the EA listen to a custom event triggered from a collection. See more details below.
eMgr (Event Manager i.e Event aggregator):
define(['backbone.wreqr'],function(Wreqr){
"use strict";
return new Wreqr.EventAggregator();
})
collection:
define([ 'underscore', 'backbone', 'eMgr', 'models/MainMenu/MM.model.category'], function(_, Backbone, eMgr, m_Category){
var CategoriesCollection = Backbone.Collection.extend({
model: m_Category,
initialize: function(options) {
console.log('CategoriesCollectionView initialized...');
this.url= 'test1';
this.fetch().then(function(){
eMgr.trigger("test1")
})
}
});
return CategoriesCollection;
});
LayoutView:
define([ 'backbone', 'underscore', 'marionette', 'eMgr',
'templates/template.mainmenu',
'collections/MainMenu/MM.collection.categories',
'layouts/MainMenu/collectionview.categories' ],
function (Backbone, _, Marionette, eMgr, template, c_Categories, cv_Categories) {
"use strict";
var CategoryLayoutView = Marionette.LayoutView.extend({
template: template['categories.layout'],
regions: {
categories : '#categories'
},
id: 'categories-layout',
initialize: function(options){
var r_categories = this.categories;
this.listenTo(eMgr, "test1", this.test);
this.categories = new c_Categories(options)
},
test: function(){
console.log("test");
var categories_layout = new cv_Categories({ collection: this.categories});
categories_layout.render()
},
onRender: function(){
},
onShow: function(){
}
});
return CategoryLayoutView;
});
As you can see above, what I'm trying to achieve is to render the CollectionView (cv_Categories) once the collection has finished loading all the data.
However it doesn't work unless I listen to the events as follows:
eMgr.listenTo(eMgr, "test1", this.test);
This will trigger the function , although I'm no longer able to access my LayoutView's methods/variables and so on. So I can't access my collection, and therefore not able to initiate my CollectionView properly.
Now the question is, am I doing anything wrong or does it all work as intended? Is there any other way to accomplish this?