Binding Custom Event Handlers Using the Coveo for Sitecore Legacy Search UI Framework jQuery Plugin
Binding Custom Event Handlers Using the Coveo for Sitecore Legacy Search UI Framework jQuery Plugin
When developing a search-driven website, you will often want to execute custom logic before or after the search query is performed. This article shows how this can be achieved.
-
Create a new Sitecore page using the
Coveo-Powered Search Pagetemplate. The page should look like this:
-
If you wanted to add custom logic, the first thing you would need to do is modify the query before it’s performed. The second thing to do is to output statistics in the browser console. To do so, edit the
CoveoSearch.ascxfile which is located in thelayouts/Coveofolder of your Sitecore instance. Then, insert the code below:Coveo.$(function() { var options = <%= Model.GetJavaScriptInitializationOptions() %>; // ADDED CODE --> Coveo.$('#search') .on('buildingQuery', function (e, args) { args.queryBuilder.expression.add('search'); }) .on('querySuccess', function (e, args) { console.log('Query returned ' + args.results.totalCount + ' results in ' + args.results.duration + 'ms.'); }); // <-- ADDED CODE Coveo.$('#search').coveoForSitecore('init', options); });Using the
onjQuery method, you attached two event handlers to thebuildingQueryandquerySuccessevents (see the list of JavaScript Search Framework Events). Since thebuildingQueryevent is fired before the query is performed, it’s the preferred event to alter the query expression. In this case, you can added thesearchterm to the query. ThequerySuccessevent, on the other hand, is fired when the query succeeds. In this case, you can output the total number of results and the query duration in the browser console. -
When reloading the page, you can see how it changes.
As you can see, by default, the search query uses the
searchterm. Notice that there are now 234 results instead of 2847. Also, if you look at the browser console, you can see the custom trace.Query returned 234 results in 30ms.