Saturday, January 17, 2009

Cookies and the problems they cause

I often use the Ext state manager to automatically manage cookies for Ext widgets. This allows the application to 'remember' user settings such as window size, location etc. The only code required is :

Ext.state.Manager.setProvider(new Ext.state.CookieProvider());


This is very powerful and simple to add to an application BUT it can cause a mountain of problems. I've been bitten twice. What sometimes happens is the cookies can end up being applied to the incorrect objects. It seems that when Ext creates DOM objects, if there is no explicit dom id, an id is created. This id is used by the cookie 'manager' to reference the objects that are monitored. This is fine, except when items are added or removed from the application. The auto generated id numbers are changed and the cookies are now referencing different objects. This problem occurs during the development process or when new application versions are released (widgets are added and removed).

How do we avoid this? Its quite simple. Just assign explicit id properties to ALL items you create. Just do this as a 'best practice'. By doing this, there are no auto generated ids and no danger of the manager referencing the wrong objects.

Using Ext.extend to extend user classes.

While learning javascript, I've fallen into the copy/paste trap of code creation. Rather than using OO constructs, I often copy a block of code, paste it and modify it slightly. This is bad bad bad so I thought I would figure out how to use Ext.Extend to take my own base class and use inheritance to extend the base functionality. There is no rocket science here but I can use this now as a template for inheriting. Code ...

// ----------- Base class (extending 'object' )  ------------------
genericBase = Ext.extend(Object, {
basevar1: 1,
constructor: function(args) {
this.basevar1 = 2;
},

baseFunc1: function(testArg) {
alert("test Arg is " + testArg + " basevar = " + this.basevar1);
}
});

// ----------- Derived class (extending 'genericBase'class ) -------
genericDerived = Ext.extend(genericBase, {
derVar: 444, // class property
constructor: function(args) {
// Call the base constructor
genericDerived.superclass.constructor.call(this, args);
},

derivedFunc1: function(testArg) {
alert("derivedFunc1 called " + testArg );
},
getBaseval: function() {
return this.basevar1;
}

});


// -------- Code to instantiate and test the classes

// First, create the object
var myobj = new genericDerived({prop1: '123', prop2: 'abc' });

// displays basevar with a get method
alert("Derived class, method call ==>" + myobj.getBaseval());

// also displays basevar, but with direct property reference
alert("explicit reference to property basevar1 ==> " + myobj.basevar1);

myobj.baseFunc1('Calling base method');
myobj.derivedFunc1('Calling derived class method');