views:

54

answers:

2

My goal here is to override a method if it isn't found, otherwise use the original method (for backwards compatibility of a library I can't alter).

This is what I have so far, but am still struggling with:

this.grid.getDataSource = function(){
        if (typeof this.grid.getDataSource.getDataSource == "undefined")
            return this.grid.getDataSource.getStore();
            else return this.grid.getDataSource.getDataSource();
    }

I want to have getDatasource() check if it exists, if not, call getStore(). If it does exist, just use the original getDatasource(). I know this breaks because I haven't figured out how to reference the parent 'this' scope. When I work around that issue I get into a recursive loop as it keeps trying to override itself. If you have a better way of doing this please let me know!

A: 

If you're sure that getDataSource() will not throw an exception, you can try

this.grid.getDataSource.getDataSource = function(){
    try {
       return this.getDataSource();
    }
    catch(ex) {
       return this.getStore();
    }
};

or you can just change

 if (typeof this.getDataSource == "undefined")

to

if (typeof this.getDataSource != "function")

UPDATE: Does this work?:

this.grid.getDataSource = function(){
    if (typeof this.getDataSource != "function")
        return this.getStore();
    else 
        return this.getDataSource();
}
Ivan Nikolchov
How do I reference the parent 'this' scope from within the function body?
Fook
you can't... just remove this.grid.getDataSource from everywhere in the function body (check my post again)
Ivan Nikolchov
Here is my new code based on your example. getDatasource isn't defined in the function body. Am I misunderstanding something?this.grid.getDataSource = function(){ try { getDataSource(); } catch(ex) { getStore(); }}
Fook
sorry, my mistake :))check my answer again...
Ivan Nikolchov
This is failing with a 'Too much recursion' error. It seems to be recursively trying to redefine getDataSource over and over again.
Fook
you're right... have you tried lincolnk's solution. It seems more elegant.
Ivan Nikolchov
+1  A: 

i think this should do what you want.

this.grid.getDataSource = 
    this.grid.getDataSource.getDataSource || this.grid.getDataSource.getStore;

this statement will try to find something that evaluates truish from left to right. when it finds that thing, it will use it as the value for the assignment. in this case if getDataSource is undefined it'll evaluate as false, and getStore will be checked. getStore exists so it'll evaluate to (roughly) true, and so the function reference will be assigned to this.grid.getDataSource.getDataSource;

lincolnk
Very elegant! Thanks!
Fook