12

how could i create an JavaScriptObject by hand when i have this class

public class Person extends JavaScriptObject{
    protected Person(){}

    public final native String FirstName()/*-{
        return this.firstName;
    }-*/; 

    public final native String LastName()/*-{
        return this.lastName;
    }-*/;
 }

i am asking because i have an array of this JavaScriptObject Peron

public JsArray<Person> persons = JavaScriptObject.createArray().cast();

and i would like to full this array with some of these Person objects

Peson a = new Person();
a.setfirstName(textField1.getText());
a.setLastName(textField2.getText());
persons.push(a)

but i doesnt know how to create such an object by hand. The values of firstName and lastName i would take from an UI component like an textField. Please help!

1 Answer 1

11

You should be able to do this?

Person a = (Person)JavaScriptObject.createObject().cast();
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks a lot. i have two questions: 1) is there a difference between your and this version -> Person a = Person.createObject()cast(); 2) how could i pass values to the person object? should i create setter methods? but in classes which extends JavaScriptObjects are no variables allowed. so how could i pass the values lastName and firstName to the object?
There is no difference between two createObject methods, since it is a static method on JavascriptObject class.
For the 2nd question, You extend JavascriptObject to access native JSON objects. The setters would be native calls that assigns the value to native Javascript variables. I think for this reason, they have put a rule that member variables are not allowed in overlay types. Please read developers.google.com/web-toolkit/doc/latest/… for more details.
class Person extends JavaScriptObject{ protected Person(){} public final native String FirstName()/*-{ return this.firstName; }-/; public final native String LastName()/-{ return this.lastName; }-/; public final native String setFirstName(String fName)/-{ this.firstName = fName; }-/; public final native String setLastName(String lName)/-{ this.lastName = lName; }-*/; } Person a = (Person)JavaScriptObject.createObject().cast(); a.setFirstName("Peter"); a.setLastName("Pan"); public JsArray<Person> persons = JavaScriptObject.createArray().cast(); persons.push(a); thx krishnakumarp

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.