Sencha Touch Framework provides various layout managers like ‘hbox’, ‘fit’ etc.
You might be curious how to add your own layout manager. addLayoutMnanager? registerLayout? …
The answer is as simple as the usage of them, because Sencha is smart enough to use the Hollywood principle design pattern. The Container class implements the private method getLayout
that will use your own layout or ‘default’ as fallback.
getLayout: function() { var layout = this.layout; if (!layout) { layout = this.link('_layout', this.link('layout', Ext.factory(this._layout || 'default', Ext.layout.Default, null, 'layout'))); layout.setContainer(this); } return layout; },
Define your own layout manager by inheriting from Ext.layout.Default
(you could use it’s subclasses as well!):
Ext.define('TaskQueue.view.layout.Rotating', { extend: 'Ext.layout.Default', requires: [ 'Ext.Anim' ], alias: 'layout.rotating', layoutClass: 'x-layout-rotating', itemClass: 'x-layout-rotating-item', _container: null, ////////////////////////////// Methods setContainer: function(container) { this.callSuper(arguments); this._container = container; container.innerElement.addCls(this.layoutClass); Ext.defer( this._applyLayout, 1000, this); }, _applyLayout: function() { // accomplish layouting here } });
Use your brand new layout manager inside a container:
Ext.define('TaskQueue.view.TaskElement', { extend: 'Ext.dataview.component.DataItem', requires: ['Ext.Container', 'Ext.Button'], xtype: 'taskelement', config: { //... }, //your own layout layout: { type: 'rotating' } }, initialize: function() { this.callParent(arguments); }, //more code //........ });
Thanks for your article – it was just what I needed.
One useful tweak I made was to override the onItemInnerStateChange method instead of using your _applyLayout method. onItemInnerStateChange is called each time a new item is added (etc.) to the container – so any programatically added items get covered by the layout logic – whereas setContainer is just called once.
Cheers! Ian
Hi Ian, thank you for sharing your optimizations! I would prefer regular event listeners as well. One issue when working with sencha is that it has a pretty huge (but well-designed) functionality. Sometimes when it comes to the more difficult things it gets harder to recognize the right solution ;-).