Created
May 25, 2018 13:04
-
-
Save francoislg/7517c7f81a45d994a60081f2d3fd476c to your computer and use it in GitHub Desktop.
Implementation of a simple "Recent keywords" component for the Coveo JavaScript Search Framework
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var RecentKeywords = (function (_super) { | |
function RecentKeywords(element, options, bindings) { | |
this.type = 'RecentKeywords'; | |
Coveo.Component.bindComponentToElement(element, this); | |
this.element = element; | |
this.options = options; | |
this.bindings = bindings; | |
this.rootElement = Coveo.$$(this.bindings.root); | |
this.rootElement.on(Coveo.QueryEvents.querySuccess, (event) => this.handleQuerySuccess(event)); | |
this.keywords = []; | |
} | |
RecentKeywords.prototype.handleQuerySuccess = function (event) { | |
this.registerKeyword(event.detail.query.q); | |
this.renderKeywords(this.keywords); | |
} | |
RecentKeywords.prototype.registerKeyword = function (keyword) { | |
if (!!keyword && this.keywords.indexOf(keyword) === -1) { | |
this.keywords.push(keyword); | |
} | |
} | |
RecentKeywords.prototype.renderKeywords = function (keywords) { | |
var currentKeyword = Coveo.state(this.bindings.root, "q"); | |
var container = document.createElement("ul"); | |
keywords | |
.filter(keyword => keyword != currentKeyword) | |
.map(keyword => this.renderOneKeyword(keyword)) | |
.forEach(child => container.appendChild(child)); | |
this.element.innerHTML = ""; | |
this.element.appendChild(container); | |
} | |
RecentKeywords.prototype.renderOneKeyword = function (keyword) { | |
var child = document.createElement("li"); | |
child.addEventListener("click", () => this.onKeywordClicked(keyword)); | |
child.innerText = keyword; | |
return child; | |
} | |
RecentKeywords.prototype.onKeywordClicked = function (keyword) { | |
Coveo.state(this.bindings.root, "q", keyword); | |
Coveo.executeQuery(this.bindings.root); | |
} | |
RecentKeywords.ID = 'RecentKeywords'; | |
Coveo.Initialization.registerAutoCreateComponent(RecentKeywords); | |
})(Coveo.Component); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment