0

I'm trying to wrap my head around a closure that I found, I understand closures on a surface level but I'm having trouble trying to understand the following.

I have a div with 3 input fields and a gray box above all of them like this: https://i.stack.imgur.com/RRYP8.png and when an input field's focus event is fired with jQuery, the grey box should change to a specific text depending on the input field.

Below is the following code to achieve this:

function main() {
  var tipText = [{
    'id': '#email',
    'tip': 'Only @pocketbook.com addresses allowed.'
  }, {
    'id': '#name',
    'tip': 'Your name must be capitalized.'
  }, {
    'id': '#employeeId',
    'tip': 'Employee IDs are found on the back of your badge.'
  }];

  function tipCallback(tip) {
    return function() {
      $('#tip').text(tip);
    };
  }

  function getTip() {
    for (var i = 0; i < tipText.length; i++) {
      var item = tipText[i];
      $(item.id).focus(tipCallback(item.tip));
    }
  }

  getTip()
}

$(document).ready(main);

I know that we need a closure since the state is not being persisted in the for loop, but I still can truly understand it.

Irins
  • 1
  • 1
  • Method just returns a function that has a reference to the text. Examples like this question: https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example shows what happens when you do not have a function, but just a reference to `i` – epascarello Nov 16 '18 at 14:46
  • 1
    While you could solve this with closures, you seem to have rather overcomplicated this. It could be achieved in a much simpler manner using `data` attributes and a common event handler. – Rory McCrossan Nov 16 '18 at 14:48
  • Here's an example of what I mentioned above: http://jsfiddle.net/7vg6xwz3/ – Rory McCrossan Nov 16 '18 at 15:39

0 Answers0