Iterating over ScriptableObject.

56 views
Skip to first unread message

Andrei Vinogradov

unread,
Dec 19, 2017, 3:45:58 AM12/19/17
to mozilla-rhino
Hello everyone. I have an issue and could not find out how to solve it.
If I define ScriptableObject like this (samples are in Kotlin):

class JavaWrapper() : ScriptableObject() {
    init
{
        defineProperty
("name", "John", PERMANENT)
        defineProperty
("surname", "Doe", PERMANENT)
   
}

   
override fun getClassName(): String = javaClass.name
}
then iterating over it would be successfull and calling
for (var property in JavaWrapper) { print(name); }
will result with "name surname" as expected.

But if I define same ScriptableObject in another way:
class JavaWrapper() : ScriptableObject() {
   
override fun getClassName(): String = javaClass.name

   
override fun get(name: String, start: Scriptable): Any {
       
return when (name) {
           
"name" -> "John"
           
"surname" -> "Doe"
           
else -> Scriptable.NOT_FOUND
       
}
   
}
}
iteration returns nothing. 

How could I modify second implementation to get iteration work successful? Sorry if my question is stupid - i'm new to Rhino. 

Ivan Vyshnevskyi

unread,
Dec 19, 2017, 8:41:39 AM12/19/17
to mozilla-rhino
Hi,

The `defineProperty()` method does much more than making
`get()` return passed value; you'll need to additionally override
at least `getIds()` and `has()` for the loop to work:

```
class Wrapper : ScriptableObject() {
    override fun getClassName(): String = javaClass.name

    override fun get(name: String, start: Scriptable): Any {
        return when (name) {
            "name" -> "John"
            "surname" -> "Doe"
            else -> Scriptable.NOT_FOUND
        }
    }

    override fun has(name: String, start: Scriptable): Boolean {
        return name == "name" || name == "surname"
    }

    override fun getIds(): Array<Any> {
        return arrayOf("name", "surname")
    }
}
```

I don't know your goal here (it looks like a http://xyproblem.info/
type of question), so could be that overriding/reimplementing
parts of `ScriptableObject` isn't the best way to achieve it.

Best,
Ivan
Reply all
Reply to author
Forward
0 new messages