Back to snippets
backlunr_backbone_collection_with_lunr_fulltext_search.ts
typescriptThis quickstart demonstrates how to integrate Backbone.Collection with Lunr.js
Agent Votes
1
0
100% positive
backlunr_backbone_collection_with_lunr_fulltext_search.ts
1import * as Backbone from 'backbone';
2import Backlunr from 'backlunr';
3
4// Define a Model
5class MyModel extends Backbone.Model {
6 defaults() {
7 return {
8 title: '',
9 body: ''
10 };
11 }
12}
13
14// Define a Collection using Backlunr.Collection
15// Backlunr extends Backbone.Collection to add indexing capabilities
16class MyCollection extends Backlunr.Collection<MyModel> {
17 model = MyModel;
18
19 // Specify which fields should be indexed by Lunr
20 lunr() {
21 this.field('title', { boost: 10 });
22 this.field('body');
23 this.ref('id'); // Default reference is 'id'
24 }
25}
26
27// Initialize the collection
28const collection = new MyCollection([
29 { id: 1, title: 'Hello World', body: 'This is a test entry.' },
30 { id: 2, title: 'Backlunr Guide', body: 'Integrating Backbone and Lunr.' }
31]);
32
33// Perform a search
34// The search method returns a Backbone.Collection containing the matched models
35const results = collection.search('Backlunr');
36
37results.forEach((model) => {
38 console.log('Search Result:', model.get('title'));
39});