0

In the avatar generator I'm working on I have several button events that do the same thing but with different body parts. I don't want to have different functions doing the same thing, so I want to use one function for all body parts.

Line 14 below uses the object propery 'AvGen.eyes.currEyesNr', but instead I want to use the one for the clicked button. What can I put in as an argument and how can I use the parameter in the function to be able to use the correct object parameter?

    1.    prevBodyBtn.on('click', function(){
    2.        if (AvGen.theBody.currBodyNr > 0) {
    3.            changePart(-1);
    4.        }
    5.    });
    6.
    7.    prevEyesBtn.on('click', function(){
    8.        if (AvGen.eyes.currEyesNr > 0) {
    9.            changePart(-1);
   10.        }
   11.    });
   12.
   13.    function changePart(direction) {
   14.        AvGen.eyes.currEyesNr += direction;  // <-- this is now always 'AvGen.eyes.currEyesNr' but should be dynamic
   15.
   16.        var body = AvGen.theBody.bodies[AvGen.theBody.currBodyNr],
   17.            eyes = AvGen.eyes.eyes[AvGen.eyes.currEyesNr],
   18.            nose = AvGen.nose.noses[AvGen.nose.currNoseNr];
   19.            mouth = AvGen.mouth.mouths[AvGen.mouth.currMouthNr];
   20.
   21.        AvGen.addSVG(body, eyes, nose, mouth);
   22.    }

2 Answers 2

2

Change names of the properties indicating current index values from currBodyNr, currEyesNr etc to currNr.

Then you can address required property of AvGen by name:

function changePart(direction, bodyPartName) {

var part = AvGen[bodyPartName];
part.currNr += direction;

...

and call it:

changePart(-1, "eyes");

or

changePart(-1, "theBody");

Another way to do it is to simply pass the body part that needs to change as a second parameter:

function changePart(direction, bodyPart) {
  bodyPart.currNr += direction;

and call it:

changePart(-1, AvGen.eyes);
Sign up to request clarification or add additional context in comments.

Comments

0

You can pass an argument to the 'click' event callback, and check which item was clicked. Than use it to pass whatever you want to the 'changePart' function. ( you can read some data you have in the clicked element for example to pass them to your function )

prevEyesBtn.on('click', function(e){

    e.currentTarget; // this is the element that was clicked for example
    if (AvGen.eyes.currEyesNr > 0) {
        changePart(-1);
    }
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.