Use of callback parameter in JS functions

0

I'm trying to use a callback parameter (I do not know if it's the correct term here) inside my constructor, which calls a function I defined, but every time I try to run the code it displays an error in the console.

Here is the button builder code:

function Botao(x, y, w, h, canvas, callback,color) {
this.x = x;
this.y = y;
this.w = w;
this.h = h;
this.cb = callback;
this.color = color;   

//render do botão.
this.render = function () {
 canvas.context.fillStyle = color || '#000'; // cor
 canvas.rect(this.x,this.y,this.w,this.h); // cria o retangulo(botão)
}

// verifica se o click foi na área do botao.
this.ontarget = function (pos) {      
 if (pos.x > this.x && pos.x < (this.x + this.w) && pos.y > this.y && pos.y <   (this.y + this.h)){
  this.cb(); // <-- meu problema/duvida!
  };  
}

and here is the code where I use it:

var teste = new Canvas(400,300,teste, 0); // cria o canvas


var bt1 = new Botao(100,100,100,100, teste, function()  {console.log("teste");}); //cria o botao



function run() {
teste.upC();//renderiza o botão

bt1.render();// renderiza o botao.
window.requestAnimationFrame(run);
}
run();


function click(evt) {
 var rectNav = teste.rectNav; ; //obtêm as coordenadas do mouse na janela do   cliente.
 var pos = {
  x: evt.clientX - rectNav.left,
  y: evt.clientY - rectNav.top
 }; 

 bt1.ontarget(pos); //detecta se o click foi no botão 
}  


cEvent('click', click);

As you can see, this is a button, where when clicking it it should return the function it assigns to callback at the time I created it, but I can not get it to work, I am using the parameter incorrectly? The function will not work in this case of the constructor?

    
asked by anonymous 06.12.2015 / 18:22

2 answers

2

I will add some corrections. You can see diff here .

In your jsFiddle code you get a syntax error, a } is missing, then I used

this.canvas.addEventListener('click', click.bind(this))

to search for clicks. I used .bid(this) to be able to use this within function click(evt) { .

I passed a string here var teste = new Canvas(400, 300, 'minhaID', 0); which in the example was as undeclared variable.

And finally I commented on //cEvent('click', click); that in jsFiddle was not defined and was giving error.

I hope I have helped!

    
06.12.2015 / 21:36
1

A button is a UI component for your application, your style (Visual) for position, dimensions, etc ... Must not be on > behavior layer , in the Javascript case.

Draw a button use CSS , "save code line" use class to componentize and generate as many instances as needed to generate others, if that is the case use the bootstrap. ("how you emphasized saving time !!").

Tip: Use Canvas (HTML5) to draw elements that are dynamic and not fixed component buttons of your interface !!

What would you doubt:

Callback and functions? Draw elements using canvas with js? About events in javascript?

    
06.12.2015 / 20:46