instantsearch.widgets.singleFacet = function singleFacet(options) { | |
// Using Hogan to compile the given template. Feel free to use anything else ;) | |
options.template = Hogan.compile(options.template); | |
var $container = $(options.container); | |
return { | |
getConfiguration: function(/*currentSearchParams*/) { | |
// Make sure the facet used for this widget is declared | |
return { | |
facets: [options.facet.attributeName] | |
} | |
}, | |
init: function(params) { | |
$container.on('click', '.facet', function(e) { | |
params.helper.removeFacetRefinement(options.facet.attributeName); | |
params.helper.addFacetRefinement(options.facet.value); | |
// Trigger a new search to take the new refinement into account | |
params.helper.search(); | |
}); | |
}, | |
render: function(params) { | |
// We know we only activate one refinement per facet, so just get the first one | |
var refinement = params.helper.getRefinements(options.facet.attributeName)[0]; | |
$container.html(options.template.render({ | |
label: options.facet.label, | |
active: refinement ? refinement.value === options.facet.value : false, | |
icon: options.icon | |
})); | |
} | |
} | |
} |
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Document</title> | |
<script src="//cdn.jsdelivr.net/jquery/2.2.0/jquery.min.js"></script> | |
<script src="//cdn.jsdelivr.net/instantsearch.js/1/instantsearch.min.js"></script> | |
<script src="./facet_widget.js"></script> | |
<script src="./main.js"></script> | |
</head> | |
<body> | |
<div class="search"> | |
<div class="facets"> | |
<div class="general"></div> | |
<div class="technology"></div> | |
<div class="comparisons"></div> | |
<div class="security"></div> | |
</div> | |
<!-- ... --> | |
</div> | |
<script id="single-facet-template" type="text/template"> | |
<div class="facet {{#active}}active{{/active}}"> | |
<img src="{{icon}}" alt="{{label}}"> | |
<span class="label">{{label}}</span> | |
</div> | |
</script> | |
</body> | |
</html> |
(function($) { | |
$(function() { | |
// ... instantsearch.js init | |
instantsearch.addWidget(instantsearch.widgets.singleFacet({ | |
container: $('.facets .general'), | |
template: $('#single-facet-template').html(), | |
facet: { | |
attributeName: 'category', | |
value: 'general', | |
label: 'General' | |
} | |
})); | |
instantsearch.addWidget(instantsearch.widgets.singleFacet({ | |
container: $('.facets .technology'), | |
template: $('#single-facet-template').html(), | |
facet: { | |
attributeName: 'category', | |
value: 'technology', | |
label: 'Technology' | |
} | |
})); | |
// ... | |
}); | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment