javascript - Issue with scoping, when calling a function in a callback -
when clicking inside canvas generate ball , move clicked location when ball get's location want remove itself. think have problem scope when calling removeball() function.
you can find working example her: jsfiddle
/* * main app logic */ function main() { this.canvas = "canvas"; this.stage = null; this.width = 0; this.height = 0; this.init(); } main.prototype.init = function() { console.clear(); this.stage = new createjs.stage(this.canvas); this.resize(); //start game loop createjs.ticker.setfps(30); createjs.ticker.addeventlistener("tick", this.gameloop); //click event handler this.stage.on("stagemousedown", function(evt) { main.fireball(evt); }); }; main.prototype.fireball = function(evt) { var bal = new bal(evt.stagex, evt.stagey); }; main.prototype.resize = function() { //resize canvas take max width this.width = window.innerwidth; this.height = math.floor(window.innerwidth * 9 / 16); this.stage.canvas.width = this.width; this.stage.canvas.height = this.height; }; main.prototype.gameloop = function() { //game loop main.stage.update(); }; /* * ball logic */ function bal(tox, toy) { this.tox = tox ; this.toy = toy; this.widthperc = 8; this.init(); } bal.prototype.width = function() { return math.floor(main.stage.canvas.width / 100 * this.widthperc); }; bal.prototype.init = function() { //create new ball this.ball = new createjs.shape(); this.ball.graphics.beginfill("green").drawcircle(0, 0, this.width()); this.ball.x = (main.stage.canvas.width / 2) - (this.width() / 2); this.ball.y = main.stage.canvas.height - 20; main.stage.addchild(this.ball); this.move(); }; bal.prototype.move = function() { //create tween cliked coordinates createjs.tween.get(this.ball).to({ x: this.tox , y: this.toy , scalex:0.4,scaley:0.4, rotation: 180 }, 750, //speed createjs.ease.none ).call(this.removeball); // <---- how can pass correct scope called function? }; bal.prototype.removeball = function() { //try remove ball main.stage.removechild(this.ball); }; var main = new main();
the solution above using bind works, there better solution. bind not available in browsers (most notably safari 5.1, modern browser). http://kangax.github.io/es5-compat-table/#function.prototype.bind
tweenjs has built-in support scoping functions when using call()
. pass scope 3rd argument.
ball.prototype.move = function() { console.log(this.tox +","+this.toy); createjs.tween.get(this.ball).to({ x: this.tox , y: this.toy , scalex:0.4,scaley:0.4, rotation: 180 }, 750, //speed createjs.ease.none ).call(this.removeball, null, this); };
you can pass array of function arguments second parameter.
tween.call(this.removeball, [this.ball], this);
Comments
Post a Comment