Skip to content. | Skip to navigation

Personal tools

>>> ''.join(word[:3].lower() for word in 'David Isaac Glick'.split())

‘davisagli’

Navigation

You are here: Home / Blog / Extending kupu's initialization with a Javascript wrapper decorator

Extending kupu's initialization with a Javascript wrapper decorator

by David Glick posted Jul 20, 2009 03:15 PM
Today I found myself struggling to do something in Javascript that I'm used to doing with ease in Python -- replace an existing method (defined by code I don't want to touch) with a wrapper that calls the original method and then also performs some additional actions. (Yeah, it's a monkey patch. But sometimes it's a cleaner and more maintainable way to extend something than the alternatives.)

In particular, I was trying to adjust the default kupu configuration without overriding kupuploneinit.js to add commands directly to the initPloneKupu method. Here's the snippet that got me there:

var augmentKupuInit = function(orig_fn) {
  return function(){
    var editor = orig_fn.apply(this, arguments);
    // do what you need to on the editor object here.
    // For example, I was trying to prevent kupu from
    // filtering the 'fb:fan' tag of Facebook's "Fan Box"
    // widget, like so:
    editor.xhtmlvalid.tagAttributes['fb:fan'] = ['*'];
    return editor;
  };
};
initPloneKupu = augmentKupuInit(initPloneKupu);

This defines a decorator function called augmentKupuInit that can be used to wrap another function. Then it uses it to wrap the original initPloneKupu method, calling the newly generated function initPloneKupu. As long as this snippet is registered in such a way that it loads after kupuploneinit.js and before the initPloneKupu method is called, it works like a charm!

(Many thanks to http://stackoverflow.com/questions/326596/how-do-i-wrap-a-function-in-javascript, which finally pointed me in the right direction.)

Mikko Ohtamaa says:
Jul 20, 2009 08:44 PM
Hi David,<p>I did something similar to catch exceptions from DOM event handlers in Firebug (otherwise they fail silently).<p>http://blog.twinapex.fi/[…]/
Navigation