Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Native method using JSNI

 
Sathiesh Kumar Vs
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am using GWT and I have created a native method in 'MyClass' to define a Javascript function named myFunction

private native void myMethod(MyClass X) /*-{
$wnd['myFunction'] = function () {
X.@ex.samples.test.MyClass::javaMethod()();
};
}-*/;

This function 'myFunction' will be called onClick of a button and that calls the javaMethod in MyClass. This as such is working fine.

Now I want the name of the function that i define to be dynamic, i.e the name 'myFunction' should be set dynamically and the javascript function should be created with that dynamic name.

The purpose of this is, the code i have written is in a common class which will be used by many other classes. So when all the classes use the same code, there are methods created with the same name in the javascript and is not working properly.

Please suggest a good way to crack it.
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Not sure where to put this topic. Let's try the GWT forum.
 
Hardik Mishra
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi

Create a class which generates dynamic name on each call.

public class JSNIHelper {

private static int requestCounter = 0;

public static String registerCallbackFunction(MyClass obj) {

String dynamicName = "jsni" + (requestCounter++);
// you can write your own logic to generate dynamic name for

createDynamicFunction(obj, dynamicName);
return callbackName;
}

private native static void createDynamicFunction(MyClass obj, String dynamicName )/*-{
tmp = function( name ){
obj.@example.myclass::execute(Ljava/lang/String;)( name );
};
$wnd[dynamicName]=tmp;
}-*/;
}



// Your Class where you will call
// Pass object of 'MyClass'

public void onClick(ClickEvent event) {
String callbackName = JSNIHelper.registerCallbackFunction(new MyClass() {

});
// do other things
}

Hope it will help....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic