1
// Using extjs 3.x var box = new Ext.Textfield { /* textField configuration */ }; var form = new Ext.FormPanel{ /* formPanel configuration */ items:[box] } 

This works fine, but I want to create multiple instances of box so that when I create multiple instances of form I don't corrupt box, also I don't want to use arrays. Please suggest a better approach to creating and managing multiple instances of an Ext.Component

2 Answers 2

5

@Mchl's answer is a good approach for making reusable components, especially when you need to override or add new behavior to an existing one. If you simply need to reuse some config settings and nothing more, you can also do something a bit simpler:

cfg = { xtype: 'textfield', width: 100, maxLength: 10 } new Ext.FormPanel({ items: [cfg, cfg] }); 

If you need to add instance-specific config fields (like id for example) you can just pass in your unique values and add the default cfg to them (applyIf will not override existing properties, it will only add properties):

new Ext.FormPanel({ items: [ Ext.applyIf({id:'foo'}, cfg), Ext.applyIf({id:'bar'}, cfg) ] }); 

One thing I would add to @Mchl's answer is that if you are going to make the effort of creating your own class, make sure you give it a custom xtype. That way you can still leverage Ext's lazy instantiation capabilities even with your own custom components, instead of having to create instances of everything at init time.

Sign up to request clarification or add additional context in comments.

4 Comments

I think this is really a classic Example
there is a problem that its not changing id when we apply in more than one items: [ Ext.apply(cfg, {id:'foo'}), Ext.apply(cfg, {id:'bar'}) ] than its not taking 'bar' its repeating 'foo'
Sorry, see my edited code that uses applyIf instead of apply -- this way the passed object is used and cfg is only applied for any additional defaults that aren't specified. Same concept as originally explained though.
Here's another approach for reusing a component's config : stackoverflow.com/a/6904404/320399
4

Extending components is the key

var MyBoxClass = Ext.extend(Ext.form.TextField,{ /* your config values */ width: ... /* this is important, see bmoeskau's comment below*/ initComponent: function() { BoxClass.superclass.initComponent.call(this); } }); var form = new Ext.FormPanel{ items: [ new MyBoxClass({fieldLabel: 'first box'}), new MyBoxClass({fieldLabel: 'second box'}), new MyBoxClass({fieldLabel: 'third box'}), ] } 

1 Comment

The example is fine, but initComponent is not actually required. What's required is that if you do override initComponent, you must call the superclass version (although this applies to any inherited method in the component life cycle that you override). In this example it can be omitted -- it will get called for you already.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.