EXTJS 4.1
I have run into a bit of a conundrum and would love to hear some other developers input on this scenario regarding ExtJS events and controller methods. I understand this topic has been covered and debated on numerous occasions but I feel that it could use a bit more delving into.
As is standard practice, I define event listeners in my Controller's init() method declaration as follows:
Ext.define("My.controller.Awesome", {
init: function(application){
/** Observe some Views */
this.control({
'my-awesome-view #saveButton':{
click: this.saveMyData
}
});
/** Listen for Events, too! */
this.on({
showAwesomeView: this.showMyAwesomeView
});
/** Application events, what fun! */
this.application.on({
showThatAwesomeView: this.showMyAwesomeView
});
}
Now, as I merrily go about coding some functionality in some other controller, I find myself needing to call showMyAwesomeView in My.controller.Awesome. I can do this in a few different ways...
Ext.define("My.controller.Other", {
/* ... class definition */
someImportant: function(){
// I can do this (Approach #1)
this.application.getController("Awesome").showMyAwesomeView();
// Or I can do this (Approach #2)
this.application.getController("Awesome").fireEvent("showAwesomeView");
// Last but not least, I can do this (Approach #3)
this.application.fireEvent("showThatAwesomeView");
}
});
To me, Approach #3 feels the most 'right'. My problem is that if I haven't instantiated the My.controller.Awesome before, the init() method has not been run yet and therefore there are no listeners established, so the fired event goes off into mystery land never to be heard of again.
I have overloaded Ext.application.getController() to call controller.init() before returning controller, therefore a controller has its init method called as soon as it is loaded (typically as a dependency in another controller). Is this bad?
In order to save on load time (my application is quite large) my controllers and their dependencies are loaded on an as-needed basis. Therefore, the majority of my controllers (and views, and data stores) are not instantiated when my application first boots therefore not init()'ed which makes firing application-wide events quite cumbersome.
I feel like I may be missing something big here, or maybe I just need to bite the bullet and ensure my controllers have been init'd before firing events. I suppose I could also put an absolutely horrific number of event listeners in the main application file and handle init'ing controllers before calling their methods accordingly, but this seems very sloppy and difficult to maintain.
Any input would be greatly appreciated, thank you for your time!
Approach #3 (this.application.fireEvent('showThatAwesomeView')) is a great solution. The use of application events results in controllers that have no assumptions about what other logic may be added or removed from the application related to this event.
Regarding your concern about controllers having been instantiated in time to be correctly bound to events, use of the Ext.app.Application controller will eliminate this. The App controller initializes all specified controllers when the App initializes. You noted a concern about start-up time related to the number of controllers. I have worked on many single page apps that have dozens and even hundreds of controllers in some cases. Keeping any init logic to a minimum should reduce any noticeable slowdown. Minified and combined scripts in place of on-demand loading has worked well to keep app start-up very fast.
Avoiding the getController method is good practice. Application logic tends to be better organized when using application events in place of logic that tightly couples controllers with each other.
Ext.define('UD.controller.c1', {
extend: 'Ext.app.Controller',
refs: [
{
selector: 'viewport',
ref: 'userview'
}
],
init: function() {
console.log("initincontroller!!");
this.control({
'viewport > panel': {
render: this.onPanelRendered
}
});
},
onPanelRendered:function(){
alert("rendered");
UD.getApplication().fireEvent('myevent');
}
});
Ext.define('UD.controller.c2', {
extend: 'Ext.app.Controller',
refs: [
{
selector: 'viewport',
ref: 'userview'
}
],
init: function() {
console.log("initincontroller!!");
UD.getApplication().on({
myevent : this.doSomething
});
},
doSomething:function(){
alert("controller2");
}
});
Related
In a big application, i now need to access some data (json api call) from asynchronously (before, those data were accessed synchronously).
I would like not to have to change components implementation to now handle this async behaviour (too risky).
I thought about $routeProvider's "resolve" feature (with promises) that helps to abstract this async behaviour out from the components/controllers.
Unfortunately i am absolutely not using routing in any way.
Is there an implementation for that? If not, where could i start?
EDIT:
how i was before (jsonData were not loaded synchronously but it was transparent thanks to systemJS features, SystemJS, Which we are throwing in garbage now, hence the question):
https://plnkr.co/edit/BSreVYNAr7sijYwEpb5G?p=preview
How i am now:
https://plnkr.co/edit/WnX0ynOqkZsmEzIxl1SI?p=preview
Watch the console to see an example of the problems that can occur now.
I kind of made it work by going like that, but i'm not completely satisfied with it (watch the config block):
https://plnkr.co/edit/P9Rv6rnboFlaFZ0OARNG?p=preview
$provide.value('$provide', $provide);
$routeProvider.otherwise({
template: '<test></test>',
controller: function ($provide, myJsonData1) {
$provide.value('myJsonData', myJsonData1);
},
resolve: {
myJsonData1: function(){
return getMyJsonData();
}
}
});
Hope this helps :)
I have found this solution from Aviv Ben-Yosef in his blog post:
angular.module('app').controller('TheCtrl', function($scope, NotifyingService) {
// ... stuff ...
NotifyingService.subscribe($scope, function somethingChanged() {
// Handle notification
});
});
angular.module('app').factory('NotifyingService', function($rootScope) {
return {
subscribe: function(scope, callback) {
var handler = $rootScope.$on('notifying-service-event', callback);
scope.$on('$destroy', handler);
},
notify: function() {
$rootScope.$emit('notifying-service-event');
}
};
});
I am thinking to do this: jsfiddle
angular.module('app').factory('NotifyingService', function() {
var handlers = {
list: []
};
return {
subscribe: function(callback) {
handlers.list.push(callback)
},
notify: function() {
handlers.list.forEach(function(handler) {
handler();
});
}
};
});
Edited: My goal is send changes to controllers in the same page. For example, there is a controller is doing something with the user and then it will notify the results to other controllers on the same page every time. I don't need to have the following abilities: unsubscribe the handlers, differentiate which handler to fire each time.
My solution seems very simple and I have not found anyone using it on internet, so I am feeling there should be something wrong with it (memory issues?).
Please point out the flaws in my solution (with resources if complicated. Ex. Memory). All I want to know is if this solution is okay to go with.
If my solution is good, please tell me, or compare pros and cons of both solutions.
Updated
Thanks to #Daniel Beck. He pointed out that my solution does need a way/function to remove handler once the controllers are out of scopes, otherwise memory leaks. I believe this is the major flaw in my solution.
Maybe I'm missing something obvious -- I'm sure someone will come along to point that out if so -- but it seems to me that the sole advantage to the first one (from the blog post) is that you don't have to remember to destroy the $on watcher when you're done with it. Its major disadvantage is that the service uses a single event name for all its $emits -- if you used this service in two different controllers, both would be triggered every time; there's no way to differentiate which handler you actually intended to trigger.
Your version shares that flaw, and additionally provides no way to remove unneeded handlers -- it appears to support only running each of a list of callbacks when its notify is called. Which is exactly what $rootScope.$emit does already.
I think you're both kinda reinventing the wheel, here.
When building an application what is the best way to setup your controllers?
I understand that routing, event listeners, and most all interactivity should be managed by the controllers, but my main controller is starting to grow out of control and I'm not sure how to best separate my logic into separate controllers without keeping them all "running" all the time...
It's okay to have them all loaded at app start-up, even with hundreds thousands of controllers. It's the view rendering that takes time.
Make sure your app is minimized and concatenated though, using sencha cmd.
In a test, I created 1000 simple controllers, like this:
Ext.define('app.controller.ControllerN', {
extend: 'Ext.app.Controller',
init: function(application) {
this.control({
buttonN1: {
click: function() {
}
},
buttonN2: {
click:function(){}
},
... 20 listeners
});
}
});
I concatenated them into one file, and loaded them in app.js like this:
Ext.application({
name:'app',
controllers:[
'Controller0',
'Controller1'
... 1000 controllers
],
launch:function(){}
}
It took ONE second from browser refresh (Chrome) until the last controller's init method was called.
I had similar problem so I divided controllers on the basis of business functionality it will support, e.g. userController does all the user related operations like login, logout, update etc whereas cartController does all the operations related to shopping cart like add to cart, apply coupons, payments etc. Since a single view can have many functionalities related to different areas of app so you can add refs to this view in multiple controllers and listen to only relevant events in corresponding controller.
I am trying to test drive a view event using Jasmine and the problem is probably best explained via code.
The view looks like:
App.testView = Backbone.View.extend({
events: { 'click .overlay': 'myEvent' },
myEvent: function(e) {
console.log('hello world')
}
The test looks something like:
describe('myEvent', function() {
it('should do something', function() {
var view = new App.testView();
view.myEvent();
// assertion will follow
});
});
The problem is that the view.myEvent method is never called (nothing logs to the console). I was trying to avoid triggering from the DOM. Has anyone had similar problems?
(Like I commented in the question, your code looks fine and should work. Your problem is not in the code you posted. If you can expand your code samples and give more info, we can take another look at it. What follows is more general advice on testing Backbone views.)
Calling the event handler function like you do is a legitimate testing strategy, but it has a couple of shortcomings.
It doesn't test that the events are wired up correctly. What you're testing is that the callback does what it's supposed to, but it doesn't test that the action is actually triggered when your user interacts with the page.
If your event handler needs to reference the event argument or the test will not work.
I prefer to test my views all the way from the event:
var view = new View().render();
view.$('.overlay').click();
expect(...).toEqual(...);
Like you said, it's generally not advisable to manipulate DOM in your tests, so this way of testing views requires that view.render does not attach anything to the DOM.
The best way to achieve this is leave the DOM manipulation to the code that's responsible for initializing the view. If you don't set an el property to the view (either in the View.extend definition or in the view constructor), Backbone will create a new, detached DOM node as view.el. This element works just like an attached node - you can manipulate its contents and trigger events on it.
So instead of...
View.extend({el: '#container'});
...or...
new View({el:'#container'});
...you should initialize your views as follows:
var view = new View();
$("#container").html(view.render().el);
Defining your views like this has multiple benefits:
Enables testing views fully without attaching them to DOM.
The views become reusable, you can create multiple instances and render them to different elements.
If your render method does some complicated DOM manipulation, it's faster to perform it on an detached node.
From a responsibility point of view you could argue that a view shouldn't know where it's placed, in the same way a model should not know what collection it should be added to. This enforces better design of view composition.
IMHO, this view rendering pattern is a general best practice, not just a testing-related special case.
What is more efficient, using events to communicate between nested Views, or keeping a reference around to call a method on. The following example shows two Views. The outer View responds to a click event, and could then use either an event, or method call to get the InnerView to respond appropriately.
InnerView = Backbone.View.extend({
initialize: function() {
this.model.bind('doSomethingEvent', this.doSomething);
},
doSomething: function() {
// This could have been called from event/trigger
// or from direction method invocation using reference.
}
});
OuterView = Backbone.View.extend({
events = {
'click' : 'handleOutViewClick'
},
render: function() {
// Create InnerView to render some model
var innerView = new InnerView({model:this.model });
$(this.el).append(innerView.render().el);
// Could store a reference to the View?
this.viewRef = innerView;
},
handleOutViewClick: function(e) {
// Should this function use a reference to the InnerView instance:
this.viewRef.doSomething();
// Or should it trigger an event on this.model that
// the InnerView is bound to?
this.someCollection.trigger('doSomethingEvent');
}
});
Probably a single method call is going to be more efficient than an event dispatch, which will involve at least 2 method calls. But I don't think you need to be concerned about which is more "efficient" here technically. Unless this is happening many times a second, you can concern yourself only with what makes for cleaner, more correct code. I think the cleanest pattern depends on the details being communicated. Here's my preference:
If it is a natural fit for outerview to manipulate models and collections, and have innerview respond via the normal backbone model/collection events, that is the cleanest.
If what's happening isn't really about the models, consider a "View Model" pattern where you model the interesting bits of state of the view as if it was a back end model, even though you have no intention of ever having that model interact with the server. Then bind your two views to events coming off the view model and have them coordinate by altering a common "view model" instance. This is a pattern I use for complicated views with lots of interdependent state not directly associated with the underlying models from the server.
If what's happening doesn't really change the models/collections and is more of a view-specific thing, a direct method dispatch will be more straightforward but also more tightly coupled. It's up to your judgement to decide when the loose coupling afforded by event dispatch merits the extra complexity and harder-to-follow control flow.