Reputation: 4570
I am trying to define a javascript type using JsInterop but could not figure out how to define an array propery inside a type.
@JsType
public interface Task
{
// this works
@JsProperty String getTitle();
@JsProperty void setTitle(String title);
}
@JsType
public interface ViewModelInterface
{
// the following works
@JsProperty String getValue();
@JsProperty void setValue(String val);
// this does not work
@JsProperty Task[] getTasks();
@JsProperty void setTasks(Task[] tasks);
}
Is there any special syntax I should use?
Update:
I have come up with a temporary solution to the problem. I tried to use JNSI together with JsInterop and because the type define is javascript type we can add any property in that type after it is initialized.
The code is here
public class ViewModel implements ViewModelInterface
{
private String value;
public ViewModel()
{
value = "";
initTasksArray();
}
public String getValue() { return value; }
public void setValue(String val) { this.value = val; }
private native void initTasksArray()
/*-{
this.tasks =
[
{ title: 'Get high enough to grab the flag' },
{ title: 'Find the Princess' }
];
}*-/;
}
This way, the tasks property can be accessed from javascript as if it is defined as a @JsProperty. This is only a temporary solution and I am sure there will be a more proper one when JsInterop formally come out.
Upvotes: 2
Views: 1261
Reputation: 4176
It should work as described. Here is an example:
@JsType
public interface Task {
@JsProperty
String getTitle();
@JsProperty
void setTitle(String title);
public static Task getTask(String title) {
return new Task() {
private String title;
@Override
public String getTitle() {
return title;
}
@Override
public void setTitle(String title) {
this.title = title;
}
};
}
}
and
@JsType
public interface ViewModel {
@JsProperty
Task[] getTasks();
@JsProperty
void setTasks(Task[] tasks);
public static ViewModel getModel() {
return new ViewModel() {
Task[] tasks;
@Override
public void setTasks(Task[] tasks) {
this.tasks = tasks;
}
@Override
public Task[] getTasks() {
return tasks;
}
};
}
}
and the Javascript:
var model = ViewModel.getModel();
model.tasks = [Task.getTask('title1'), Task.getTask('title2')];
alert(model.tasks);
Upvotes: 1