[Java] GWT jsni and jQuery

博客首页 » Java GWT jsni and jQuery

发布于 09 Dec 2014 01:56
标签 blog
Question: Use jquery inside GWT jsni

http://stackoverflow.com/questions/16030089/use-jquery-inside-gwt-jsni

I am not able to use

$("#"+profileId).offset().top
from inside my gwt jsni function. I tried this

$wnd.$("#"+profileId).offset().top
but this is also not working. I feel i am missing syntax here. Could anybody help

Answer:
Three solutions for this question:

1- Your Jsni code looks fine except that you have to enclose it in the corresponding native function and return a double (or any other number type if you want gwt to make the casting).

native double getTop(String profileId) /*-{
return $wnd.$("#" + profileId).offset().top;
}-*/;
If you wanted to see errors through your UncaughExceptionHandler you should wrap your code in a $entry block

native double getTop(String profileId) /*-{
return $entry(function(data) {
return $wnd.$("#" + profileId).offset().top;
});
}-*/;
2- But, instead of using jQuery, I encourage you to use gwt-query aka gQuery. So you dont have to load jQuery in your .html and yo dont need to deal with jsni in your app.

With gQquery you have almost the same jQuery syntax but in java, so you have type safe, refactoring, testing …. But also, you will have dozens of utilities (simplest ajax, promises, selectors, etc) which are not in the gwt core.

gQuery is a light-weight library, fully rewritten from scratch in gwt. It is NOT a wrapper of the jQuery library (like is incorrectly said in the other answer), you dont have to include jquery.js in your pages.

Like with any other gwt library, the gwt compiler would get rid of anything you dont use from gquery. In your approach, your app has to load all the jquery stuff.

So in your case, and using gquery write this code in your .java classes:

import static com.google.gwt.query.client.GQuery.*;
… onModuleLoad() {
int top = $("#"+profileId).offset().top;
}
3- Finally, you have the option of using pure gwt code to get the offset of an element, if you know its id:

int top = DOM.getElementById(profileId).getOffsetTop();


本页面的文字允许在知识共享 署名-相同方式共享 3.0协议和GNU自由文档许可证下修改和再使用,仅有一个特殊要求,请用链接方式注明文章引用出处及作者。请协助维护作者合法权益。


系列文章

文章列表

  • Java GWT jsni and jQuery

这篇文章对你有帮助吗,投个票吧?

rating: 0+x

留下你的评论

Add a New Comment
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License