View Full Version : Referencing private objects when extending a component (TreePanel)

14 Oct 2010, 12:48 PM
Hi guys -

I'm extending a TreePanel and I'm having trouble figuring out why this snippet of code is invalid:

myTreePanel = Ext.extend(Ext.tree.TreePanel,{

title:'Asset Tree',
collapseButton:new Ext.Button({
text:'Collapse All',




I know there are other ways to rewrite this and make it work, such as instantiating the button inside of the "buttons" array, but I'm wondering why my code is invalid? It causes one of those weird "c is undefined" errors in Ext. I know I'm missing something, but I don't quite see what it is. Why are you not allowed to reference a property in this way?

Thanks in advance for any help.

14 Oct 2010, 12:56 PM
At the point where collapseButton is added to the buttons array, this is still one level outside of your config object because the object has not been created yet.

I guess it could be thought of as one of those Chicken/Egg conflicts.

14 Oct 2010, 12:58 PM
Ah, I think I see what you mean. So what is the correct way to do this? Do I just need to override the constructor completely and create collapseButton there?

14 Oct 2010, 1:01 PM
I always do this type of thing within initComponent.

Also, your collapseButton property holds a complex data type, which is a reference. This means your button would be shared between each instance of that main component. Generally you should only place simple data types and functions at this top level.

14 Oct 2010, 1:10 PM
Also, keep in mind that objects and arrays are passed by reference in JavaScript.
NOTE: I did not see VinylFox post... was writing the example hehe...

//anObject will be part of MyObject.prototype and all instanciated classes of MyObject will share the same instance of anObject.
//You normally don't want to do this, unless you really know what you are doing.

MyObject = Ext.extend(Object, {
simpleValue: 1, //passed by value, changing this property won't affect all MyObject instances
anObject: {} //passed by reference, changing anything on this object will affect all MyObject instances

//Instead you should do this
MyObject = Ext.extend(Object, {
simpleValue: 1,
initComponent: function() {
this.anObject = {}; //Now a new instance of Object will be hold in the anObject property of each new instances of MyObject


//Simple Example

function Test(){}
Test.prototype.test = { num: 1};
var test1 = new Test();
var test2 = new Test();
test1.test.num = 2;
console.log(test2.test.num); //This will also print 2 even if we changed the num property of the test property on test1.

14 Oct 2010, 3:41 PM
Hey guys, thanks a lot for the info. This was really helpful. I knew that javascript objects were passed by reference, but I don't think I really understood the implications until I read these explanations and examples. I appreciate the help!

14 Oct 2010, 5:56 PM
Awesome! Glad I could help.