A lot of Sencha Touch examples I found online, don't really focus on proper view encapsulation. So the Controller listens to every single button's event even if the button is deep nested inside a view. In other words the internals of the view leak through which is never a good thing.
I found one good tutorial that encourages you to create meaningful views that listen to local events and raise meaningful business events etc.
http://miamicoder.com/2012/how-to-create-a-sencha-touch-2-app-part-2/
However, one thing that I couldn't really figure out so far is how to best cache nested component instances. Consider this example:
Ext.define("NotesApp.view.NotesListContainer", {
extend: "Ext.Container",
alias: "widget.noteslistcontainer",
initialize: function () {
this.callParent(arguments);
var newButton = {
xtype: "button",
text: 'New',
ui: 'action',
handler: this.onNewButtonTap,
scope: this
};
var topToolbar = {
xtype: "toolbar",
title: 'My Notes',
docked: "top",
items: [
{ xtype: 'spacer' },
newButton
]
};
this.add([topToolbar]);
},
onNewButtonTap: function () {
console.log("newNoteCommand");
this.fireEvent("newNoteCommand", this);
},
config: {
layout: {
type: 'fit'
}
}
});
Let's say we want to add a method setSpecialUIState
to our NotesListContainer
. When it's called we want to do something with the newButton
(e.g. hide it). How would I gain access to the newButton
instance without misusing Ext.getComp()
for that? Can I set it as an instance variable? How is the canonical way?
UPDATE
I just tried this as Nikolaj Borisik suggested.
this._newButton = this.add([{
xtype: "button",
text: 'New',
ui: 'action',
handler: this.onNewButtonTap,
scope: this
}];
That works like a charm. I just don't know if its idiomatic to do so or if there are any downsides I might be missing. Otherwise I would highly recommend to do this. Sencha aside, it's much better to compose meaningful views that abstract away coherent UI parts. That's much better than leak every single button through to the controller and fiddle directly with them.
So I wonder if there are any downsides of this approach?