Using class methods inside connectors

i’m using angular with instansearch.js, is there a way to pass or access class variables inside the callback function of the pagination connector?

E.G. I want to access class methods/functions of “this” (the parent class) inside renderFn

ngOnInit() {   
    
    const makePagination = connectPagination(this.renderFn);
    this.instantSearchService.search.addWidget(makePagination({
       containerNode: $('.pagination'),
    }));

 }

function renderFn(PaginationRenderingOptions, isFirstRendering) {
  
  this.function() <-- this is always undefined currently
 
  if (isFirstRendering) {
    PaginationRenderingOptions.widgetParams.containerNode.html('<ul></ul>');
  }

  // remove event listeners before replacing markup
  PaginationRenderingOptions.widgetParams.containerNode
    .find('a[data-page]')
    .each(function() { $(this).off('click'); });

  var pages = PaginationRenderingOptions.pages
    .map(function(page) {
      return '<li style="display: inline-block; margin-right: 10px;">' +
        '<a href="' + PaginationRenderingOptions.createURL(page) + '" data-page="' + page + '">' +
        (parseInt(page) + 1) + '</a></li>';
    });

  PaginationRenderingOptions.widgetParams.containerNode
    .find('ul')
    .html(pages);

  PaginationRenderingOptions.widgetParams.containerNode
    .find('a[data-page]')
    .each(function() {
      $(this).on('click', function(event) {
        event.preventDefault();
        PaginationRenderingOptions.refine($(this).data('page'));
      });
    });
}

thanks in advance.

Just to clarify, is there a reason you are not using Angular InstantSearch and its BaseWidget? That way you can use the regular angular life cycles to make your component.

I’m using this https://github.com/algolia/instantsearch.js as we think its the more flexible option and we’re pretty ok with it (and using something else will take us back a lot)

Anyways, any chance i can make what i’m doing work? I’m doing this because algolia’s estimate for nbHits when exaustive search is true is way off the actual figure (6k - 8k off the actual count for 20k results) using facets.

Hi @jdonald
I agree with @haroen using Angular InstantSearch would probably be easier.
To answer your question directly: you pass the context of your class to renderFn by calling .bind:
Instead of

connectPagination(this.renderFn)

write

connectPagination(this.renderFn.bind(this))

You can read more about .bind here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind

I hope this helps!

1 Like

Hi Youcef,

Thank you for the solution.

We’ll definitely look at switching to Angular Instantsearch as soon as we have the time and resource to do so