How to define custom JS objects in ScalaJS












0















The phaser game library has an API where you pass a custom object when starting a game scene (docs). This data object can be any javascript object at all and can be retrieved from within the scene from the scene's settings. My question is how do I define this object in the phaser facades in a generic way and define a strongly typed version in my own code?



So far I have just referenced the object as a js.Object in the phaser APIs and cast it to my own type when the scene is created:



@js.native
trait ScenePlugin extends js.Object {
def start(key: SceneKey, data: js.UndefOr[js.Object] = js.undefined): ScenePlugin
}

@js.annotation.ScalaJSDefined
class LevelConfig(
val key: LevelKey,
val loadingImage: Option[AssetKey] = None) extends js.Object

@ScalaJSDefined
class LoadScene extends Scene {
private val loader = new SceneLoader(scene = this)
private var levelConfig: LevelConfig = _

override def preload(): Unit = {
levelConfig = sys.settings.data.asInstanceOf[LevelConfig]
}

...
}


This works but I'm not happy with it because I have to cast the data object. Any errors with the actual object that gets passed to the ScenePlugin.start() will cause errors during runtime and I may as well have just used vanilla JS. Also, my LevelConfig cannot be a case class as I get the compile error Classes and objects extending js.Any may not have a case modifier which I don't fully understand.



Has anyone dealt with this situation before and what did you do to get around it? I'm guessing the issue stems from the library which is being used so perhaps I need to create some kind of wrapper around Phaser's Scene class to deal with this? I'm quite new to ScalaJS and am looking to improve my understanding so any explanations with solutions would be much appreciated (and upvoted). Thanks very much!










share|improve this question























  • Question: do you want to define the facade in the completely-generic way? If the facade is highly-general (allowing varied types), then your strongly-typed code isn't going to have much choice but to cast. But keep in mind that your facade can be stricter than the underlying JS library, provided that it sufficiently describes all the data you will be passing back and forth.

    – Justin du Coeur
    Jan 2 at 23:42











  • I don't really care about what type the facade has as long as it's not hard-coded to a specific object. Each game will have have multiple scene objects which may have different data objects passed to them.

    – William Carter
    Jan 3 at 18:43






  • 1





    In which case, the cast may be a necessary evil. This isn't actually unusual -- Scala.js is the exception to the usual rule that you should always avoid asInstanceOf. When you are at the border between strongly-typed Scala and weakly-typed JavaScript, it's often necessary. I usually wrap the casts in API code, and then call those APIs from my application code.

    – Justin du Coeur
    Jan 3 at 23:05
















0















The phaser game library has an API where you pass a custom object when starting a game scene (docs). This data object can be any javascript object at all and can be retrieved from within the scene from the scene's settings. My question is how do I define this object in the phaser facades in a generic way and define a strongly typed version in my own code?



So far I have just referenced the object as a js.Object in the phaser APIs and cast it to my own type when the scene is created:



@js.native
trait ScenePlugin extends js.Object {
def start(key: SceneKey, data: js.UndefOr[js.Object] = js.undefined): ScenePlugin
}

@js.annotation.ScalaJSDefined
class LevelConfig(
val key: LevelKey,
val loadingImage: Option[AssetKey] = None) extends js.Object

@ScalaJSDefined
class LoadScene extends Scene {
private val loader = new SceneLoader(scene = this)
private var levelConfig: LevelConfig = _

override def preload(): Unit = {
levelConfig = sys.settings.data.asInstanceOf[LevelConfig]
}

...
}


This works but I'm not happy with it because I have to cast the data object. Any errors with the actual object that gets passed to the ScenePlugin.start() will cause errors during runtime and I may as well have just used vanilla JS. Also, my LevelConfig cannot be a case class as I get the compile error Classes and objects extending js.Any may not have a case modifier which I don't fully understand.



Has anyone dealt with this situation before and what did you do to get around it? I'm guessing the issue stems from the library which is being used so perhaps I need to create some kind of wrapper around Phaser's Scene class to deal with this? I'm quite new to ScalaJS and am looking to improve my understanding so any explanations with solutions would be much appreciated (and upvoted). Thanks very much!










share|improve this question























  • Question: do you want to define the facade in the completely-generic way? If the facade is highly-general (allowing varied types), then your strongly-typed code isn't going to have much choice but to cast. But keep in mind that your facade can be stricter than the underlying JS library, provided that it sufficiently describes all the data you will be passing back and forth.

    – Justin du Coeur
    Jan 2 at 23:42











  • I don't really care about what type the facade has as long as it's not hard-coded to a specific object. Each game will have have multiple scene objects which may have different data objects passed to them.

    – William Carter
    Jan 3 at 18:43






  • 1





    In which case, the cast may be a necessary evil. This isn't actually unusual -- Scala.js is the exception to the usual rule that you should always avoid asInstanceOf. When you are at the border between strongly-typed Scala and weakly-typed JavaScript, it's often necessary. I usually wrap the casts in API code, and then call those APIs from my application code.

    – Justin du Coeur
    Jan 3 at 23:05














0












0








0








The phaser game library has an API where you pass a custom object when starting a game scene (docs). This data object can be any javascript object at all and can be retrieved from within the scene from the scene's settings. My question is how do I define this object in the phaser facades in a generic way and define a strongly typed version in my own code?



So far I have just referenced the object as a js.Object in the phaser APIs and cast it to my own type when the scene is created:



@js.native
trait ScenePlugin extends js.Object {
def start(key: SceneKey, data: js.UndefOr[js.Object] = js.undefined): ScenePlugin
}

@js.annotation.ScalaJSDefined
class LevelConfig(
val key: LevelKey,
val loadingImage: Option[AssetKey] = None) extends js.Object

@ScalaJSDefined
class LoadScene extends Scene {
private val loader = new SceneLoader(scene = this)
private var levelConfig: LevelConfig = _

override def preload(): Unit = {
levelConfig = sys.settings.data.asInstanceOf[LevelConfig]
}

...
}


This works but I'm not happy with it because I have to cast the data object. Any errors with the actual object that gets passed to the ScenePlugin.start() will cause errors during runtime and I may as well have just used vanilla JS. Also, my LevelConfig cannot be a case class as I get the compile error Classes and objects extending js.Any may not have a case modifier which I don't fully understand.



Has anyone dealt with this situation before and what did you do to get around it? I'm guessing the issue stems from the library which is being used so perhaps I need to create some kind of wrapper around Phaser's Scene class to deal with this? I'm quite new to ScalaJS and am looking to improve my understanding so any explanations with solutions would be much appreciated (and upvoted). Thanks very much!










share|improve this question














The phaser game library has an API where you pass a custom object when starting a game scene (docs). This data object can be any javascript object at all and can be retrieved from within the scene from the scene's settings. My question is how do I define this object in the phaser facades in a generic way and define a strongly typed version in my own code?



So far I have just referenced the object as a js.Object in the phaser APIs and cast it to my own type when the scene is created:



@js.native
trait ScenePlugin extends js.Object {
def start(key: SceneKey, data: js.UndefOr[js.Object] = js.undefined): ScenePlugin
}

@js.annotation.ScalaJSDefined
class LevelConfig(
val key: LevelKey,
val loadingImage: Option[AssetKey] = None) extends js.Object

@ScalaJSDefined
class LoadScene extends Scene {
private val loader = new SceneLoader(scene = this)
private var levelConfig: LevelConfig = _

override def preload(): Unit = {
levelConfig = sys.settings.data.asInstanceOf[LevelConfig]
}

...
}


This works but I'm not happy with it because I have to cast the data object. Any errors with the actual object that gets passed to the ScenePlugin.start() will cause errors during runtime and I may as well have just used vanilla JS. Also, my LevelConfig cannot be a case class as I get the compile error Classes and objects extending js.Any may not have a case modifier which I don't fully understand.



Has anyone dealt with this situation before and what did you do to get around it? I'm guessing the issue stems from the library which is being used so perhaps I need to create some kind of wrapper around Phaser's Scene class to deal with this? I'm quite new to ScalaJS and am looking to improve my understanding so any explanations with solutions would be much appreciated (and upvoted). Thanks very much!







phaser-framework scala.js






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jan 2 at 23:23









William CarterWilliam Carter

765819




765819













  • Question: do you want to define the facade in the completely-generic way? If the facade is highly-general (allowing varied types), then your strongly-typed code isn't going to have much choice but to cast. But keep in mind that your facade can be stricter than the underlying JS library, provided that it sufficiently describes all the data you will be passing back and forth.

    – Justin du Coeur
    Jan 2 at 23:42











  • I don't really care about what type the facade has as long as it's not hard-coded to a specific object. Each game will have have multiple scene objects which may have different data objects passed to them.

    – William Carter
    Jan 3 at 18:43






  • 1





    In which case, the cast may be a necessary evil. This isn't actually unusual -- Scala.js is the exception to the usual rule that you should always avoid asInstanceOf. When you are at the border between strongly-typed Scala and weakly-typed JavaScript, it's often necessary. I usually wrap the casts in API code, and then call those APIs from my application code.

    – Justin du Coeur
    Jan 3 at 23:05



















  • Question: do you want to define the facade in the completely-generic way? If the facade is highly-general (allowing varied types), then your strongly-typed code isn't going to have much choice but to cast. But keep in mind that your facade can be stricter than the underlying JS library, provided that it sufficiently describes all the data you will be passing back and forth.

    – Justin du Coeur
    Jan 2 at 23:42











  • I don't really care about what type the facade has as long as it's not hard-coded to a specific object. Each game will have have multiple scene objects which may have different data objects passed to them.

    – William Carter
    Jan 3 at 18:43






  • 1





    In which case, the cast may be a necessary evil. This isn't actually unusual -- Scala.js is the exception to the usual rule that you should always avoid asInstanceOf. When you are at the border between strongly-typed Scala and weakly-typed JavaScript, it's often necessary. I usually wrap the casts in API code, and then call those APIs from my application code.

    – Justin du Coeur
    Jan 3 at 23:05

















Question: do you want to define the facade in the completely-generic way? If the facade is highly-general (allowing varied types), then your strongly-typed code isn't going to have much choice but to cast. But keep in mind that your facade can be stricter than the underlying JS library, provided that it sufficiently describes all the data you will be passing back and forth.

– Justin du Coeur
Jan 2 at 23:42





Question: do you want to define the facade in the completely-generic way? If the facade is highly-general (allowing varied types), then your strongly-typed code isn't going to have much choice but to cast. But keep in mind that your facade can be stricter than the underlying JS library, provided that it sufficiently describes all the data you will be passing back and forth.

– Justin du Coeur
Jan 2 at 23:42













I don't really care about what type the facade has as long as it's not hard-coded to a specific object. Each game will have have multiple scene objects which may have different data objects passed to them.

– William Carter
Jan 3 at 18:43





I don't really care about what type the facade has as long as it's not hard-coded to a specific object. Each game will have have multiple scene objects which may have different data objects passed to them.

– William Carter
Jan 3 at 18:43




1




1





In which case, the cast may be a necessary evil. This isn't actually unusual -- Scala.js is the exception to the usual rule that you should always avoid asInstanceOf. When you are at the border between strongly-typed Scala and weakly-typed JavaScript, it's often necessary. I usually wrap the casts in API code, and then call those APIs from my application code.

– Justin du Coeur
Jan 3 at 23:05





In which case, the cast may be a necessary evil. This isn't actually unusual -- Scala.js is the exception to the usual rule that you should always avoid asInstanceOf. When you are at the border between strongly-typed Scala and weakly-typed JavaScript, it's often necessary. I usually wrap the casts in API code, and then call those APIs from my application code.

– Justin du Coeur
Jan 3 at 23:05












1 Answer
1






active

oldest

votes


















1














I followed Justin du Coeur's comment suggestion of modifying the Phaser facade's. I defined a non-native trait for a SceneData object and updated the native Scene facade to have two types which subclasses of Scene must override. Phaser scenes are abstract and intended to be overridden so I think this works well:



class Scene(config: SceneConfig) extends js.Object {
type Key <: SceneKey
type Data <: SceneData

def scene: ScenePlugin = js.native
def data: Data = js.native

def preload(): Unit = js.native
def create(): Unit = js.native
def update(time: Double, delta: Double): Unit = js.native
}

object Scene {
trait SceneKey { def value: String }
implicit def keyAsString(id: SceneKey): String = id.value

trait SceneData extends js.Object
}

@js.native
trait ScenePlugin extends js.Object {
def start[S <: Scene](id: String, data: js.UndefOr[S#Data] = js.undefined): ScenePlugin = js.native
}


And here's a simplified example of a scene in my game:



class LoadScene extends Scene(LoadScene.Config) {
override type Key = LoadId.type
override type Data = GameAssets

override def preload(): Unit = {
createLoadBar()
loadAssets(data)
}

private def createLoadBar(): Unit = { ... }
private def loadAssets(config: GameAssets): Unit = { ... }

override def create(): Unit = {
scene.start[GameScene](GameId)
}
}

object LoadScene {
case object LoadId extends SceneKey { val value = "loading" }
val Config: SceneConfig = ...
}


I quite like this because it's now impossible to start a scene with another scene's config type.






share|improve this answer


























    Your Answer






    StackExchange.ifUsing("editor", function () {
    StackExchange.using("externalEditor", function () {
    StackExchange.using("snippets", function () {
    StackExchange.snippets.init();
    });
    });
    }, "code-snippets");

    StackExchange.ready(function() {
    var channelOptions = {
    tags: "".split(" "),
    id: "1"
    };
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function() {
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled) {
    StackExchange.using("snippets", function() {
    createEditor();
    });
    }
    else {
    createEditor();
    }
    });

    function createEditor() {
    StackExchange.prepareEditor({
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader: {
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    },
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    });


    }
    });














    draft saved

    draft discarded


















    StackExchange.ready(
    function () {
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54014479%2fhow-to-define-custom-js-objects-in-scalajs%23new-answer', 'question_page');
    }
    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    I followed Justin du Coeur's comment suggestion of modifying the Phaser facade's. I defined a non-native trait for a SceneData object and updated the native Scene facade to have two types which subclasses of Scene must override. Phaser scenes are abstract and intended to be overridden so I think this works well:



    class Scene(config: SceneConfig) extends js.Object {
    type Key <: SceneKey
    type Data <: SceneData

    def scene: ScenePlugin = js.native
    def data: Data = js.native

    def preload(): Unit = js.native
    def create(): Unit = js.native
    def update(time: Double, delta: Double): Unit = js.native
    }

    object Scene {
    trait SceneKey { def value: String }
    implicit def keyAsString(id: SceneKey): String = id.value

    trait SceneData extends js.Object
    }

    @js.native
    trait ScenePlugin extends js.Object {
    def start[S <: Scene](id: String, data: js.UndefOr[S#Data] = js.undefined): ScenePlugin = js.native
    }


    And here's a simplified example of a scene in my game:



    class LoadScene extends Scene(LoadScene.Config) {
    override type Key = LoadId.type
    override type Data = GameAssets

    override def preload(): Unit = {
    createLoadBar()
    loadAssets(data)
    }

    private def createLoadBar(): Unit = { ... }
    private def loadAssets(config: GameAssets): Unit = { ... }

    override def create(): Unit = {
    scene.start[GameScene](GameId)
    }
    }

    object LoadScene {
    case object LoadId extends SceneKey { val value = "loading" }
    val Config: SceneConfig = ...
    }


    I quite like this because it's now impossible to start a scene with another scene's config type.






    share|improve this answer






























      1














      I followed Justin du Coeur's comment suggestion of modifying the Phaser facade's. I defined a non-native trait for a SceneData object and updated the native Scene facade to have two types which subclasses of Scene must override. Phaser scenes are abstract and intended to be overridden so I think this works well:



      class Scene(config: SceneConfig) extends js.Object {
      type Key <: SceneKey
      type Data <: SceneData

      def scene: ScenePlugin = js.native
      def data: Data = js.native

      def preload(): Unit = js.native
      def create(): Unit = js.native
      def update(time: Double, delta: Double): Unit = js.native
      }

      object Scene {
      trait SceneKey { def value: String }
      implicit def keyAsString(id: SceneKey): String = id.value

      trait SceneData extends js.Object
      }

      @js.native
      trait ScenePlugin extends js.Object {
      def start[S <: Scene](id: String, data: js.UndefOr[S#Data] = js.undefined): ScenePlugin = js.native
      }


      And here's a simplified example of a scene in my game:



      class LoadScene extends Scene(LoadScene.Config) {
      override type Key = LoadId.type
      override type Data = GameAssets

      override def preload(): Unit = {
      createLoadBar()
      loadAssets(data)
      }

      private def createLoadBar(): Unit = { ... }
      private def loadAssets(config: GameAssets): Unit = { ... }

      override def create(): Unit = {
      scene.start[GameScene](GameId)
      }
      }

      object LoadScene {
      case object LoadId extends SceneKey { val value = "loading" }
      val Config: SceneConfig = ...
      }


      I quite like this because it's now impossible to start a scene with another scene's config type.






      share|improve this answer




























        1












        1








        1







        I followed Justin du Coeur's comment suggestion of modifying the Phaser facade's. I defined a non-native trait for a SceneData object and updated the native Scene facade to have two types which subclasses of Scene must override. Phaser scenes are abstract and intended to be overridden so I think this works well:



        class Scene(config: SceneConfig) extends js.Object {
        type Key <: SceneKey
        type Data <: SceneData

        def scene: ScenePlugin = js.native
        def data: Data = js.native

        def preload(): Unit = js.native
        def create(): Unit = js.native
        def update(time: Double, delta: Double): Unit = js.native
        }

        object Scene {
        trait SceneKey { def value: String }
        implicit def keyAsString(id: SceneKey): String = id.value

        trait SceneData extends js.Object
        }

        @js.native
        trait ScenePlugin extends js.Object {
        def start[S <: Scene](id: String, data: js.UndefOr[S#Data] = js.undefined): ScenePlugin = js.native
        }


        And here's a simplified example of a scene in my game:



        class LoadScene extends Scene(LoadScene.Config) {
        override type Key = LoadId.type
        override type Data = GameAssets

        override def preload(): Unit = {
        createLoadBar()
        loadAssets(data)
        }

        private def createLoadBar(): Unit = { ... }
        private def loadAssets(config: GameAssets): Unit = { ... }

        override def create(): Unit = {
        scene.start[GameScene](GameId)
        }
        }

        object LoadScene {
        case object LoadId extends SceneKey { val value = "loading" }
        val Config: SceneConfig = ...
        }


        I quite like this because it's now impossible to start a scene with another scene's config type.






        share|improve this answer















        I followed Justin du Coeur's comment suggestion of modifying the Phaser facade's. I defined a non-native trait for a SceneData object and updated the native Scene facade to have two types which subclasses of Scene must override. Phaser scenes are abstract and intended to be overridden so I think this works well:



        class Scene(config: SceneConfig) extends js.Object {
        type Key <: SceneKey
        type Data <: SceneData

        def scene: ScenePlugin = js.native
        def data: Data = js.native

        def preload(): Unit = js.native
        def create(): Unit = js.native
        def update(time: Double, delta: Double): Unit = js.native
        }

        object Scene {
        trait SceneKey { def value: String }
        implicit def keyAsString(id: SceneKey): String = id.value

        trait SceneData extends js.Object
        }

        @js.native
        trait ScenePlugin extends js.Object {
        def start[S <: Scene](id: String, data: js.UndefOr[S#Data] = js.undefined): ScenePlugin = js.native
        }


        And here's a simplified example of a scene in my game:



        class LoadScene extends Scene(LoadScene.Config) {
        override type Key = LoadId.type
        override type Data = GameAssets

        override def preload(): Unit = {
        createLoadBar()
        loadAssets(data)
        }

        private def createLoadBar(): Unit = { ... }
        private def loadAssets(config: GameAssets): Unit = { ... }

        override def create(): Unit = {
        scene.start[GameScene](GameId)
        }
        }

        object LoadScene {
        case object LoadId extends SceneKey { val value = "loading" }
        val Config: SceneConfig = ...
        }


        I quite like this because it's now impossible to start a scene with another scene's config type.







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 5 at 12:54

























        answered Jan 5 at 12:46









        William CarterWilliam Carter

        765819




        765819
































            draft saved

            draft discarded




















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid



            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f54014479%2fhow-to-define-custom-js-objects-in-scalajs%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            'app-layout' is not a known element: how to share Component with different Modules

            android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

            WPF add header to Image with URL pettitions [duplicate]