Adding 'Show All' to menu

I would like to use the regular Menu widget with the addition of a “Show All” option. It doesn’t seem like this is possible with the standard widget. I did some searching, and found this thread here which I built my code off of.

The problem is that the on('click', function(x) { ... } is never applied to the items. I believe this is because the items are not yet inserted when the isFirstRendering portion of the code is run. A few console.log tests seem to verify this.

What is the best way to solve this? Is there a better way to build this widget? A setTimeout() function would probably solve the issue, but it seems like a very inelegant solution, and I’m not sure it would work across all devices.

Also: are all the standard widgets built using these connectors? Is there a way for me to see their code, so that if I wanted to use a widget with its regular functionality but only small adjustments, I could?

function menuRenderFn(MenuRenderingOptions, isFirstRendering) {
  if(isFirstRendering) {
    MenuRenderingOptions.widgetParams.containerNode
      .html('<div class="myContainer"></div>');

    MenuRenderingOptions.widgetParams.containerNode
      .find('a')
      .on('click', function(event) {
        MenuRenderingOptions.refine(event.target.value);
      });
  }

  var options = MenuRenderingOptions.items.map(function(item) {
		if(item.label === '1') item.label = 'Black';
  	if(item.label === '0') item.label = 'White';

    if(item.isRefined) {
    	return '<a class="myItemClass active" value="' + item.value + '">' + item.label + '</a>'
    } else {
      return '<a class="myItemClass" value="' + item.value + '">' + item.label + '</a>';
    }
  });

  // Add 'All' option
  const refinedItem = MenuRenderingOptions.items.find(function(item) { return item.isRefined });
  options.unshift(
  	refinedItem
    	? '<a class="myItemClass active" value="' + refinedItem.value + '">Show All</a>'
      : '<a class="myItemClass" value="all">Show All</a>'
  );

  MenuRenderingOptions.widgetParams.containerNode
    .find('div')
    .html(options);
}

Hey there,

I would suggest to bind the click event to the containerNode to delegate the events to the children links (a nodes). You can learn more about event delegation on this guide for jQuery.

If you specifically want to detect a click on a link, you can have a look at the MutationObserver API.

All our internal implementations use connectors, you can find their implementations on GitHub.

Cheers,