Tutorials: Basic Example - Nnubes256/Dorito GitHub Wiki

Basic example

Let's see the basic example:

var MyMod = {
    myVar: 0,
    hello: ""
};
dorito.Events.DoritoInitialized.add(function() {
    console.log("Dorito is done! Let's init ourselves!");
    MyMod.myVar = 256;
    MyMod.hello = "world";
});
dorito.Events.GameLoaded.add(function() {
    console.log("Test mod works!");
    console.log("myVar is " + MyMod.myVar);
    console.log("Hello " + MyMod.hello + "!");
});

Variable initialization

First, the MyMod object:

var MyMod = {
    myVar: 0,
    hello: ""
};

Let's remember a thing: what Dorito does(currently) is to inject addons that are executed like an scripts in a page. This means that their context is the global object. As this object can be accesed by everyone, this might result in variable corruption from other mods, etc. To prevent cluttering this global object with our variables, we can create a single object where we can store these(in this case the MyMod object). This is optional, but recommended.

Another, even better(but more advanced) way is to enclose everything in an immediately-invoked function expression, like this:

(function(){
    var MyMod = {
        myVar: 0,
        hello: ""
    };
    dorito.Events.DoritoInitialized.add(function() {
        console.log("Dorito is done! Let's init ourselves!");
        MyMod.myVar = 256;
        MyMod.hello = "world";
    });
    dorito.Events.GameLoaded.add(function() {
        console.log("Test mod works!");
        console.log("myVar is " + MyMod.myVar);
        console.log("Hello " + MyMod.hello + "!");
    });
})()

This design pattern makes variables you declare belong to the function's local scope instead of cluttering the global scope.

Event listeners

dorito.Events.DoritoInitialized.add(function() {
    console.log("Dorito is done! Let's init ourselves!");
    MyMod.myVar = 256;
    MyMod.hello = "World";
});
dorito.Events.GameLoaded.add(function() {
    console.log("Test mod works!");
    console.log("myVar is " + MyMod.myVar);
    console.log("Hello " + MyMod.hello + "!");
});

Obviously, we'll want to both Dorito and our game to load before we do anything(executing code before they load will probably lead to really weird bugs in your side). For this purpose, Dorito provides some events that you can hook into:

  • DoritoInitialized: called when all mods have been injected. Use this to initialize your variables and stuff.
  • GameLoaded: the game is ready to launch AND the DoritoInitialized event has been fired. Now you can execute code!

The strict execution order of both events allows us to init our variables in DoritoInitialized and to access them in GameLoaded.

Result

This code's console output will be:

Dorito is done! Let's init ourselves!
Test mod works!
myVar is 256
Hello World!

That's it for now!