Skip to content

Reuters tutorial: step 5

jpmckinney edited this page Sep 13, 2010 · 13 revisions

Table of Contents

We’ve been through the steps for creating a new widget twice now, so without further ado:

Create a new widget CurrentSearchWidget.js:

(function ($) {
AjaxSolr.CurrentSearchWidget = AjaxSolr.AbstractWidget.extend({
});
})(jQuery);

Add the JavaScript file:

<script type="text/javascript" src="widgets/CurrentSearchWidget.js"></script>

And add an instance of the widget to the Manager in reuters.js:

Manager.addWidget(new AjaxSolr.CurrentSearchWidget({
  id: 'currentsearch',
  target: '#selection',
}));

Now, let’s implement afterRequest to display the current filters:

afterRequest: function () {
  var self = this;
  var links = [];

  var fq = this.manager.store.values('fq');
  for (var i = 0, l = fq.length; i < l; i++) {
    links.push($('<a href="#"/>').text('(x) ' + fq[i]).click(self.removeFacet(fq[i])));
  }
  if (links.length) {
    AjaxSolr.theme('list_items', this.target, links);
  }
  else {
    $(this.target).html('<div>Viewing all documents!</div>');
  }
},

removeFacet: function (facet) {
  var self = this;
  return function () {
    if (self.manager.store.removeByValue('fq', facet)) {
      self.manager.doRequest(0);
    }
    return false;
  };
}

The above afterRequest method collects all the fq parameter values using the ParameterStore values API method. For each parameter value, it creates a link displaying the parameter value which, when clicked, removes the parameter value (using the ParameterStore removeByValue API method) and sends a request to Solr. (The removeFacet method is necessary to work around JavaScript closures.) If any links were created in this manner, it displays the links. If no links were created, it displays the text “Viewing all documents!”

Lastly, let’s add a link to remove all current filters. Add the following snippet before if (links.length) { ...:

if (links.length > 1) {
  links.unshift($('<a href="#"/>').text('remove all').click(function () {
    self.manager.store.remove('fq');
    self.manager.doRequest(0);
    return false;
  }));
}

If more than one link was created, it creates a link displaying the words “remove all,” which, when clicked, removes all fq parameters (using the ParameterStore remove API method) and sends a request to Solr.

[What we have so far]

Now that we have filters, let’s add a free-text widget to finish the basics.

Clone this wiki locally