Attach ExtJS MVC controllers to DOM elements, not components - extjs

Is there a way to use the Ext.app.Controller control() method, but pass in a DOM query? I have a page that contains standard links and would like to add a click handler to them even though they were not created as Ext Buttons.
I've tried
Ext.define('app.controller.TabController', {
extend: 'Ext.app.Controller',
init: function() {
console.log("init");
this.control({
'a': {
click: this.changeTab
}
});
},
changeTab: function() {
alert("new tab!");
}
});
But clicking on links does not fire the alert.
Is there a way to specify a CSS selector with this.control? Or does it only work with components?

I asked this question at SenchaCon this year, the Sencha developers stated that their intent is that DOM listeners should be attached within your view, and the view should abstract them into more meaningful component events and refire them.
For example, suppose you're creating a view called UserGallery that shows a grid of people's faces. Within your UserGallery view class, you would listen for the DOM click event on the <img> tag to receive event and target, and then the view might fire a component event called "userselected" and pass the model instance for the clicked user instead of the DOM target.
The end goal is that only your views should be concerned with things like interface events and DOM elements while the application-level controller only deals with meaningful user intents. Your application and controller code shouldn't be coupled to your markup structure or interface implementation at all.
Sample View
Ext.define('MyApp.view.UserGallery', {
extend: 'Ext.Component'
,xtype: 'usergallery'
,tpl: '<tpl for="users"><img src="{avatar_src}" data-ID="{id}"></tpl>'
,initComponent: function() {
this.addEvents('userselected');
this.callParent(arguments);
}
,afterRender: function() {
this.mon(this.el, 'click', this.onUserClick, this, {delegate: 'img'});
this.callParent(arguments);
}
,onUserClick: function(ev, t) {
ev.stopEvent();
var userId = Ext.fly(t).getAttribute('data-ID');
this.fireEvent('userselected', this, userId, ev);
}
});
Notes on views
Extend "Ext.Component" when all you want is a managed <div>, Ext.Panel is a lot heavier to support things like titlebars, toolbars, collapsing, etc.
Use "managed" listeners when attaching listeners to DOM elements from a component (see Component.mon). Listeners managed by a components will be automatically released when that component gets destroyed
When listening for the same event from multiple DOM elements, use the "delegate" event option and attach the listener to their common parent rather than to individual elements. This performs better and lets you create / destroy child elements arbitrarily without worrying about continuously attaching/removing event listeners to each child. Avoid using something like .select('img').on('click', handler)
When firing an event from a view, Sencha's convention is that the first parameter to the event be scope -- a reference to the view that fired the event. This is convenient when the event is being handled from a controller where you'll need the actual scope of the event handler to be the controller.
Sample Controller
Ext.define('app.controller.myController', {
extend: 'Ext.app.Controller'
,init: function() {
this.control({
'usergallery': {
userselected: function(galleryView, userId, ev) {
this.openUserProfile(userID);
}
}
});
}
,openUserProfile: function(userId) {
alert('load another view here');
}
});

I have found a work around for this problem. It isn't as direct as one may hope, but it leaves all of your "action" code in the controller.
requirment: Wrap the html section of your page in an actual Ext.Component. This will likely be the case either way. So for instance, you may have a simple view that contains your HTML as follows:
Ext.define('app.view.myView', {
extend: 'Ext.panel.Panel',
alias: 'widget.myView',
title: 'My Cool Panel',
html: '<div>This link will open a window</div><br /> <label for="myInput">Type here: </label><input name="myInput" type="text" value="" />',
initComponent: function(){
var me = this;
me.callParent(arguments);
}
});
Then in the controller you use the afterrender event to apply listeners to your DOM elements. In the example below I illustrate both links (a element) and input elements:
Ext.define('app.controller.myController', {
extend: 'Ext.app.Controller',
init: function() {
this.control({
'myView': {
afterrender: function(cmp){
var me = this; //the controller
var inputs = cmp.getEl().select('input'); // will grab all DOM inputs
inputs.on('keyup', function(evt, el, o){
me.testFunction(el); //you can call a function here
});
var links = cmp.getEl().select('a'); //will grab all DOM a elements (links)
links.on('click', function(evt, el, o){
//or you can write your code inline here
Ext.Msg.show({
title: 'OMG!',
msg: 'The controller handled the "a" element! OMG!'
});
});
}
}
});
},
testFunction: function(el) {
var str = 'You typed ' + el.value;
Ext.Msg.show({
title: 'WOW!',
msg: str
});
}
});
And there you have it, DOM elements handled within the controller and adhering to the MVC architecture!

No, this seems not to be possible. The Ext.EventBus listens to events fired by ExtJS components. Your standard DOM elements do not fire those events. Additionally the query is checked with the ExtJS componets is( String selector ) method, wich can't be called by DOM elements. Someone might correct me if i'm wrong, but so i'm quite sure it's not possible, unfortunately.

I also have a solution that works around this problem. I use this technique regardless though as it has other benefits: I created an application wide messaging bus. Its an object in my application that extends Observable, and defines a few events. I can then trigger those events from anywere in my app, including html a links. Any component that wants to listen to those events can relay them and they'll fire as if fired from that component.
Ext.define('Lib.MessageBus', {
extend: 'Ext.util.Observable',
constructor: function() {
this.addEvents(
"event1",
"event2"
);
this.callParent(arguments);
}
});
Then, each other compnent can add this after initialisation:
this.relayEvents('Lib.MessageBus', ['event1','event2']);
and then listen to those events.
You can trigger the events from anything by doing:
Lib.MessageBus.fireEvent('event1', 'param a', 'param b')
and you can do that from anything including html links.
Very handy to fire off events from one part of the app to another.

I had the same problem recently (mixing mvc with some non components).
Just thought I'd throw this in as an answer as it seems pretty simple and works for me :)
Ext.define('app.controller.TabController', {
extend: 'Ext.app.Controller',
init: function() {
console.log("init");
this.control({
/* 'a': {
click: this.changeTab
} */
});
var link = Ext.dom.Query.selectNode('a');
Ext.get(link).on('click', this.changeTab);
},
changeTab: function() {
alert("new tab!");
}
});

Related

Where to use listeners and where to use controller - Sencha Touch 2

I am confused between the proper usage of Listeners vs Controllers
E.g. for the same button, I can make the handler for the button-tap event in the button description itself as :
Ext.Viewport.add({
xtype: 'button',
centered: true,
text: 'My Button',
listeners: {
tap: function() {
alert("You tapped me");
}
}
});
and also as in a separate controller as below.
Ext.define("NotesApp.controller.Notes", {
extend: "Ext.app.Controller",
config: {
refs: {
newNoteBtn: Get reference to button here
},
control: {
newNoteBtn: {
tap: "onNewNote"
}
}
},
onNewNote: function () {
console.log("onNewNote");
}
});
What is the best practice, and are there trade-offs?
Thanks
To controller or not to controller, that is the question.
Well, technically, nothing would prevent you from doing one or the other. I have established a way how to decide for myself:
I install listeners on view if the job they are doing does not cross boundaries of the view. If we take form as an example, disabling and enabling, showing and hiding of fields, if it depends only on the state of the form stay within the form - no controller.
I delegate the logic to a controller if the action in one view (a button click, for example) influences another view or the whole application.
Again, these are my preferences, you can have another.

How to run conroller methods within a event in Ext JS 4.2 (Sencha Architect)

I have in Architect the following structure.
A controller that includes a view (example MyPanelView)
In the MyPanelView, you can have a button, and give it an itemId. Then you can
bind it to a click event. You can use the click event (inline) without the controller,
or you can move the event to the controller. That works fine.
But what about these events? afterrender, beforerender, etc..? If you move this up to
the controller, the event does not get fired there.
Since this is not working, how could I acces the controller methods within
the afterrender function of the panel?
onAfterrenderMyPanelView : function(component, eOpts) {
this.getRefToOtherPanel() //not working
}
Thanks in advance! I'm lost..
Chris.
You can set up listeners and event handlers in your controller like this (example from the Sencha docs):
Ext.define('MyApp.controller.Users', {
extend: 'Ext.app.Controller',
init: function() {
this.control({
'viewport > panel': { //<-- ComponentQuery
render: this.onPanelRendered //<-- event handler
}
});
},
onPanelRendered: function() {
console.log('The panel was rendered');
}
});

Backbone.js per attribute rendering (multiple small views vs multiple templates per view )

I have a model and a view. The view displays attributes of a model and allows the user to manipulate these attributes. The problem is that when an attribute is modified it re-renders the whole view which causes a lot of problems for me.
Example blur event on a text input saves the new input to an attribute and thus fires render. Which means that if the user clicked from that text input straight to a button on the same view that event will never fire as the first event that fires will be blur causing the whole view to re-render and thus losing the button click event.
I have two ideas:
Have a single view where every attribute is in a separate template. Then I bind to a particular attribute change event and in render I update only the html of the changed attribute. This seems like a hack, as there is a lot of work to force the view to update only the changed attribute. It will add a lot of unnecessary complexity to an already complex view.
Create a master view which consists of views, where each of them represents a model's attribute. This will create a lot of views, with nearly no functionality.
I seem to prefer the 2. option. What do you think? What are the best practices? Is there any better way to handle this?
I think you can do this quite easily.
Take a step back and think about where you are binding your events. It seems that you are binding them directly on top of each individual element instead of using a parent delegate.
Here's an example
Backbone.View.extend({
el: $("div.parent"),
events: function() {
this.$el.on("click", "input[type=button]", function(){});
// jquery cross browser on this
this.$el.on("blur", "input[type=text]", function(){});
},
initialize: function() {
this.model.bind("change", this.render, this);
},
render: function() {
this.$el.html('<input type="text" /><input type="button" />');
}
});
Here's what el and it's structure looks like
<div class="parent">
<input type="text" />
<input type="button" />
</div>
So this.$el points to div.parent. I can constantly rerender the contents of this.$el, and as long as the html structure dosen't change, I don't have to worry about events getting unbound. The other solution is that if I really cannot do delegation, I would just call the events method whenever I render again.
Like you said yourself, both of your options seem very complex. But sometimes additionaly complexity is a necessary evil. However, if the updated fields are something relatively simple (like binding a value to an element or an input field), I would simply update the DOM elements without creating additional View/Template abstractions on top of them.
Say you have a model:
var person = new Person({ firstName: 'John', lastName: 'Lennon', instrument:'Guitar' });
And a view which renders the following template:
<div>First Name: <span class="firstName">{{firstName}}</span></div>
<div>Last Name: <span class="lastName">{{lastName}}</span></div>
<div>Instrument: <input class="instrument" value="{{instrument}}"></input></div>
You could declare in the view which property change should update which element, and bind the model change event to a function which updates them:
var PersonView = Backbone.View.extend({
//convention: propertyName+"Changed"
//specify handler as map of selector->method or a function.
firstNameChanged: { '.firstName': 'text' },
lastNameChanged: { '.lastName': 'text' },
instrumentChanged: { '.instrument': 'val' },
otherFieldChanged: function(val) { //do something else },
initialize: function (opts) {
this.model.on('change', this.update, this);
},
//called when change event is fired
update: function(state) {
_.each(state.changed, function(val, key) {
var handler = this[key + "Changed"];
//handler specified for property?
if(handler) {
//if its a function execute it
if(_.isFunction(handler)) {
handler(val);
//if its an object assume it's a selector->method map
} else if(_.isObject(handler)) {
_.each(handler, function(prop, selector) {
this.$(selector)[prop](val);
}, this);
}
}
}, this);
}
A solution like this doesn't scale to very complex views, because you have to add classed elements to the DOM and maintain them in the View code. But for simpler cases this might work quite well.
In addition it's always good to try to compose views of multiple, smaller views, if they naturally divide into sections. That way you can avoid the need to update single fields separately.

Is there really no click event for all ExtJS components

I'm learning extjs 4.1 and I can't find click event on most of the components - I'm I blind or I'm unable to react on click on other components than button?
What is the reason? HTML supports click on all elements.
Every component can have the click event exposed at the element level. Some components like Ext.button.Button have a click event at the component level.
Here is a nice way to add a click event on a panel:
new Ext.panel.Panel({
listeners: {
click: this.handlePanelClick,
element: 'el'
}
});
edit to respond to comment
The element string is a any element that is a property of the component.
new Ext.panel.Panel({
listeners: {
click: function() {
alert('you clicked the body');
},
element: 'body'
}
});
The Ext docs have a more thorough explanation http://docs.sencha.com/ext-js/4-1/#!/api/Ext.util.Observable-method-addListener
You can add any DOM event pretty easily by accessing the Ext.dom.Element object that almost all visible components contain once it has been rendered.
Simply add a listener to the afterrender event that adds the event you want to the dom object.
Ext.create('Ext.panel.Panel', {
// other panel configs ...
listeners: {
'afterrender': function(panel) {
panel.el.on('click', function() {
alert('clicked');
});
}
}
});
I think there is also a way to do it for all components of a class that extends Ext.util.Observable (all visible components). I haven't done it before so you would have to play around with that.
Using a self-referencing managed listener (cleanest imo):
Ext.create('Ext.panel.Panel', {
listeners: {
'afterrender': function(panel) {
this.mon(this.getEl(), 'click', this.onClick, this)
}
},
onClick: function() {
alert("mmm mon mon mon");
}
});
If you are only listening to click event you can also do this
xtype: 'container',
listeners: {
el: {
click: function() {
alert('I clicked');
},
scope: this
}
}
If you need to listen to an event that the Ext.dom.Element does not fire, you will need to attach it in the 'render' listener, like others have suggested.

Can't understand MVC example code given by EXT JS

I am going through the Example on MVC and i don't understand the following
1.) I didnt understand what itemdblclick means ? I know it means double clicks and when we d-click on the grid the function coresponding to it gets executed, but i don't think this is a pre-difined function. So from where does it come from. Imagine there is a button and i want it to log a message to the console saying it was clicked (as shown below) what will itemdblclick be ?
Ext.define('AM.controller.Users', {
extend: 'Ext.app.Controller',
views: [
'user.List'
],
init: function() {
this.control({
'userlist': {
itemdblclick: this.editUser
}
});
},
editUser: function(grid, record) {
console.log('Double clicked on ' + record.get('name'));
}
});
itemdblclick is the name of event. You look for events supported by the control you're working with. For example for button it will be here: http://docs.sencha.com/ext-js/4-0/#!/api/Ext.button.Button
And then specify event you're subscribing to.
In the this.control block, you are setting up event listeners. So itemdblclick is an event name that is fired by the userlist control.

Resources