Export to GitHub

gwt-exporter - issue #9

Static constructors


Posted on Mar 3, 2009 by Happy Monkey

I have got a class SomeClass which can be instantiated only once for each DOM Element. It simply has protected constructor and static method:

public static SomeClass getInstance(Element elem);

This method returns instance of Widget previously created for Element elem or creates new one. Every things works well, except I do not like static constructors in JavaScript. Instead I prefer to have constructors witch does all tricks. I mean something like:

$wnd.Widget = function (elem) { if ($wnd.Widget.instances[elem]) return $wnd.Widget.instances[elem]; else return this; }

This is only example of such constructor - in gwt-exporter this should be implemented in more generic way.

Attached patch adds new annotation @ExportConstructor, which instructs gwt-exporter to treat method as a constructor. Annotated method should be declared static and should return instance of class it is declared in (this conditions are check during code generation).

JavaScript constructor looks like that:

  $wnd.autoguard.SomeClass = function() {
    if(...)) {
  ....
    }
    else if(arguments.length == 2) {
  .... // code generated for normal constructor
    }
    else if(arguments.length == 1) {
  // code generated for static constructor getInstance():
      var x =

@pl.autoguard.client.SomeClass::getInstance(Lcom/google/gwt/user/client/Element;)(arguments[0]); return @org.timepedia.exporter.client.ExporterUtil::wrap(Lorg/timepedia/exporter/client/Exportable;)(x); } return this; // this is not necessary }

One more thing about @ExportConstructor: annotated methods are not automatically added to set of exportable methods. So in following example method getInstance() would not be exported:

  class SomeClass implements Exportable {

 @ExportConstructor
 public static SomeClass getInstance(Element elem) {
    ...
 }
  }

Programmer should add @Export annotation (with class or with method).

Let me know if you find this useful.

Radoslaw Kintzi

Attachments

Comment #1

Posted on Aug 1, 2011 by Grumpy Elephant

fixed in r58

Thank you for contributing

Status: Fixed

Labels:
Type-Defect Priority-Medium