views:

55

answers:

2

extjs 3.x ,
var box = new Ext.Textfield { .../* somr thing /...... };
var form = new Ext.formpanel{
..../
settings here for form */
items:[ box ]
}

actually this works fine but problem is i want to create multiple instances of it "box".so that when i create multiple forms box i do not sacrifice the settings box , also i donot want to use arrays or please suggest some better coading technique than this

+2  A: 

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'}),
  ]

}

Mchl
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.
bmoeskau
Thanks for clarifying that!
Mchl
+3  A: 

@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.

bmoeskau
I think this is really a classic Example
Extjs Commander
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'
Extjs Commander
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.
bmoeskau