简体   繁体   中英

What is the right way to pass parameters into callback functions?

It's a working example. As you can see I'm calling setElemHeight function with a returned value from getElemHeight . But i think it's a bad practice to pass value instead of function.

Option 1) I can wrap it in anonymous function like this:

function () { getElemHeight('.map-svg') }

Option 2) I can call it inside setElemHeight function and pass parameter there, but i think it would ruin Open Closed Principle.

My question is: What is the right way to pass parameters into callback functions?

Thanks.

function(elem) {
  return $(elem).height()
}

function setElemHeight(elem, callback, offset) {
  let elemHeight = callback
  $(elem).height(elemHeight - offset)
}
$(window).on('load resize', function() {
  setElemHeight('#dealersTabContent', getElemHeight('.map-svg'), 190)
})

Passing a value to a function is just fine, unless the height of the element changes over time.

If it changes, you'll want to re-calculate the height on each call of the event handler. If it does not, you can just pass the value in, since it will always use the same value anyway.

Also, this line:

 let elemHeight = callback

If callback is a function, this doesn't actually invoke the callback, it just assigns the function to a new variable.
If you want elemHeight to get the return value, you'll need to do this instead:

 let elemHeight = callback() // <== Notice the parenthesis

If it's a value, you probably want to change the name.

As for the Open Closed principle, I think that in JS, being a dynamic, weakly typed language, this will probably mostly apply to modules and not a specific code snippet. There are some tricks for creating encapsulation in JS and for allowing extension only in certain places, but generally you can plug anything you want anywhere, so I just don't worry about it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM