Pregunta

So I want to call a function when a html-defined button is pressed. The problem is I can't reach/find it, the console logs the error "Reference error: function not defined".

The stripped-down layout of my output.js (combined & compiled typescript) looks like so:

window.onload = function () {
    var game = new SpaceGen.Game();
};
var __extends = this.__extends || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    __.prototype = b.prototype;
    d.prototype = new __();
};
var SpaceGen;

(function (SpaceGen) {
    var Game = (function (_super) {
        __extends(Game, _super);
        function Game() {
            _super.call(this, 512, 640, Phaser.AUTO, 'content');

            this.state.add('state_World', SpaceGen.World, false);

            this.state.start('state_World');
        }
        return Game;
    })(Phaser.Game);
    SpaceGen.Game = Game;
})(SpaceGen || (SpaceGen = {}));

var SpaceGen;
(function (SpaceGen) {
    var World = (function (_super) {
        __extends(World, _super);
        function World() {
            _super.apply(this, arguments);
            ...
        }    

        World.prototype.getSeed = function () {
            console.log("submitted");
            var seed = document.getElementById('seed')[0].value;
        };        
        return World;
    })(Phaser.State);
    SpaceGen.World = World;
})(SpaceGen || (SpaceGen = {}));

I call the function in the html file like so:

<input id="seed" type="number" name="seed" value="111" />
<button onclick="getSeed()">Start</button>

The output.js (and phaser.js, since this is uses phaser) have been loaded and everything (else) works just fine.

How do I call the function? I tried quite a bit like this.game.getSeed(), game.getSeed() and many more, just fishing in the dark if that's a valid saying.

¿Fue útil?

Solución

getSeed is a method of SpaceGen.World. You have instantiated it as a private variable in your onload handler so there's no way to access it from an attribute handler.

The simplest solution would be to create a global. But the best way is to register the handler with a script instead of through an HTML attribute

<button id="my-button">Start</button>

window.onload = function () {
    var world = new SpaceGen.World();
    var button = document.getElementById('my-button');
    button.addEventListener('click', function(){
        alert(world.getSeed());
    })        
};
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top