Overriding Canvas.init

I may be trying to do something I shouldn’t here, but I’d like Isomorphic’s take on it. I’m trying to override the Canvas.init method in such a way that whenever any Canvas in created in my application, it runs a piece of code. Specifically, I want every Canvas to check for two properties called “profileEnabled” and “profileProperties”, and if they’re found, to load the given properties from a set of user profile properties loaded when the application starts.

So I did this:

isc.Canvas.addMethods({
    baseInit: isc.Canvas.init,
    init: function() {
        if (this.profileEnabled && isc.isAn.Array(this.profileProperties) && this.profileProperties.length>0)
            for (var iProp=0;iProp<this.profileProperties.length;iProp++) {
                if (this[this.profileProperties[iProp]])
                    alert(this.profileProperties[iProp]); // this is just a test line
            }
    
        this.baseInit(arguments);
    }
});

As you might have guessed, this doesn’t work. My Canvases refuse to load, and I can’t even get the Developer Console to open with this bit of code in here. So, obviously my clever solution was less clever than I thought.

I realize this is dangerous and most likely foolish to try to play around with such fundamental bits of the SmartClient framework. Still, can I do it? How? I want to avoid having to individually override init() for every single Canvas subclass in my application (almost every Canvas loads a few initial properties from the user’s profile). So how could I do this generically without breaking SmartClient?

Hmm. Maybe I can override Canvas.create()?

Hi ledifni,

If you were creating a new tree of classes with this behavior, it would be as simple as using Super().

Since you actually want to retroactively apply this behavior to all Canvas-derived classes, it’s slightly more complicated, but doable in several ways. Probably the most straightforward way is in fact to move isc.Canvas.create to a different property slot, install a new method, and call the original create().

Just be sure that you pass through all arguments and return the return value - you might want to look at the original definition of create() in Class.js to understand more about it.

Thanks, I got it working. Here’s my fixed code:

isc.Class.addClassMethods({
    baseCreate: isc.Class.create,
    create: function(A,B,C,D,E,F,G,H,I,J,K,L,M) {
        var instance=this.baseCreate(A,B,C,D,E,F,G,H,I,J,K,L,M);
    
        if (instance.profileEnabled && isc.isAn.Array(instance.profileProperties) && instance.profileProperties.length>0)
            for (var iProp=0;iProp<instance.profileProperties.length;iProp++) {
                if (instance[instance.profileProperties[iProp]])
                    alert(instance.profileProperties[iProp]);
            }
    
        return instance;
    }
});