PDA

View Full Version : passing handler function with json



citizen
30 Jul 2009, 7:40 AM
I load my toolbar via json (different users must see different menus), but I can't tell extjs what the handler for each entry is :



var my_handler = function() {
alert('TODO');
}

var north_toolbar = new Ext.Toolbar();

Ext.Ajax.request({
url: '/ext/get_north_menu_config',
success: function(result, request){
// for fast debug
var returned_json = "[{ text: 'alfa', menu: [{ text: 'alfa_one', menu: [{ text: 'alfa_two', handler: 'my_handler' }]}]}]"
north_toolbar.add(Ext.util.JSON.decode(returned_json));
north_toolbar.doLayout();
},
now, 'my_handler' with quotes won't work, makes sense, tries to use a string as handler ...
but if I remove the quotes from 'my_handler' the toolbar doesn't render and firebug says :

my_handler is not defined
eval()10 (riga 1)
anonymous()ext-all-debug.js (riga 11527)
anonymous()ext-all-debug.js (riga 11649)
anonymous()layout.js (riga 25)
handleResponse()ext-all-debug.js (riga 8550)
f()ext-base.js (riga 7)
anonymous()ext-base.js (riga 7)


chrome://firebug/content/blank.gif return eval("(" + json + ')'); \n

30 Jul 2009, 7:44 AM
that's correct. why are you passing a string as a handler?

Also, no need to call doLayout if the toolbar is not rendered.

citizen
30 Jul 2009, 8:05 AM
Right, as a string won't work, what I'm saying is that also :



var returned_json = "[{ text: 'alfa', menu: [{ text: 'alfa_one', menu: [{ text: 'alfa_two', handler: my_handler }]}]}]"


is not working, with the interpreter complaining :

my_handler is not defined, even if the function my_handler is defined a few lines before ...

30 Jul 2009, 8:15 AM
The returned_json is a STRING, u can't pass this STRING into extjs as an toolbar OBJECT.

Actually I don't know what u are going to do, but:

if you want string:
var returned_json = "[{ text: 'alfa', menu: [{ text: 'alfa_one', menu: [{ text: 'alfa_two', handler:" + my_handler + "}]}]}]"

if you want object:
var returned_json = [{ text: 'alfa', menu: [{ text: 'alfa_one', menu: [{ text: 'alfa_two', handler: my_handler }]}]}]

30 Jul 2009, 8:20 AM
I see the problem. my_handler is not within scope of the JSON that is being constructed.

That said, move my_handler to a global name space such as MyApp.utils.my_handler, this way it can be scoped from anywhere.

citizen
30 Jul 2009, 8:50 AM
works, thanks, you saved me from an ictus.