1

Im using D3 and JS.

I have a function that creates buttons and one of the parameters is onClick which runs when the buttons is clicked (obviously).

For example:

simpleButton(imageURL, width, height, title, onClick){
.attr("xlink:href", imageUrl) //-original image
    .attr( "width", width) //-icon width
    .attr( "height", height) //-icon height
    .on("click", onClick)
    .append("svg:title")
    .text(title); //-give the button a title
}

Now one of my buttons I'm going to use to hide some shapes (i.e. set visibility:hidden).

So I have created another function to hide the selection, something like:

hideSelection(selection){
    selection.classed("hidden", true);
}

This function takes on one parameter so that I can pass through what I want to hide.

So for example what I thought would work looks like this:

simpleButton("\images\dog", 100, 100, "dog", hideSelection(dog));

Now, this does work, but it works straight away without me clicking. I know it's because I'm calling the hideSelection straight away because of the parenthesis-().

But my question is, how do I stop calling this function straight away when running it ? How do I run a function with parameters via another function that has parameters (if that makes any sense at all)?

1
  • ah I didn't know, but now I do :) Thanks Commented Jan 8, 2015 at 10:53

2 Answers 2

2

You should wrap it in an anonymous function:

simpleButton("\images\dog",100,100, "dog", function() {
  hideSelection(dog)
});

This function has access to the dog variable because it's a closure - a function that has access to the parent scope at the time it was created.

Sign up to request clarification or add additional context in comments.

1 Comment

closures !! was reading about that last week, totally forgot. Thank you, all working perfectly :)) Ill choose this as the answer once it lets me
2

You are indeed calling hideSelection(dog) immediately and passing the result of that to simpleButton - you need to pass a reference to a function. The easiest way to do that is to wrap it in another function:

simpleButton("\\images\\dog", 100, 100, "dog", function() {
    hideSelection(dog)
});

(P.S.You probably want to escape the \s in the image path too)

1 Comment

@joews beat you to it im afraid :L thank you though, understand it now :) and the link to the image was just an example, thanks again :)

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.