Search highlight in Elasticsearch (javascript) - javascript

I am having a problem with result highlighting in Elasticsearch. My query works, it does return results, but they are NOT highlighted... so I've been searching but I can't find what I'm doing wrong!
This is my code:
function search(searchInput){
emptyTable();
client.search({
index: 'movies',
size: 5,
body: {
query: {
//match: {_all: searchInput}
"term": {
"_all" : searchInput
}
},
"highlight": {
"require_field_match": true,
"fields": {
"_all": {
"pre_tags": [
"<b>"
],
"post_tags": [
"</b>"
]
}
}
}
}
}).then(function (resp) {
var hits = resp.hits.hits;
var hitcount = resp.hits.total;
if(!jQuery.isEmptyObject(hits)){
console.log(hits);
$.each(hits, function(key,obj) {
if(key%2==0){
$('#table').append('<tr><td>'+obj._source.imdbid+'</td><td>'+obj._source.name+'</td><td>'+obj._source.desc+'</td></tr>');
}else{
$('#table').append('<tr class="even"><td>'+obj._source.imdbid+'</td><td>'+obj._source.name+'</td><td>'+obj._source.desc+'</td></tr>');
}
});
}
$('#count').html("Aantal resultaten: "+hitcount);
});
}
I am searching data then putting it in a table, works fine. But the highlighting is not working at all. Please help me out!

I was having this same problem, and it turns out that when you specify the highlight parameter, elasticsearch returns not only the '_source' fields, but also 'highlight' fields. Upon further inspection, the ES docs seem to confirm this:
there will be another element in each search hit, called highlight, which includes the highlighted fields and the highlighted fragments
So, to get this working, you'd need to swap '_source' for 'highlight' in your code:
<td>'+obj.highlight.name+'</td>
I also found that ES also puts the highlight response in square brackets, so in my case, (using AngularJS) I accessed the value as follows:
// ...ng-repeat=result in results...
<p ng-bind-html="result.highlight.body[0]">{{result.highlight.body[0]}}</p>

that simplier version works for me too, elasticsearch 5, node 8.7, elasticsearch.js node module:
response = await client.search({
index: indexName,
type: indexType,
q: query,
highlight: {
fields: {
"*": {
"pre_tags": ["<b>"],
"post_tags": ["</b>"]
}
}
}
}

Working version for ES 2.2.
In the highlight section of the query use
require_field_match: false,
function search(searchInput){
emptyTable();
client.search({
index: 'movies',
size: 5,
body: {
query: {
//match: {_all: searchInput}
term: {
_all: searchText
}
},
highlight: {
require_field_match: false,
fields: {
"*": {
"pre_tags": [
"<b>"
],
"post_tags": [
"</b>"
]
}
}
}
}
}).then(function (resp) {
var hits = resp.hits.hits;
var hitcount = resp.hits.total;
if(!jQuery.isEmptyObject(hits)){
console.log(hits);
$.each(hits, function(key,obj) {
if(key%2==0){
// All highlight fields here...
$('#table').append('<tr><td>'+obj.highlight.imdbid+'</td><td>'+obj.highlight.name+'</td><td>'+obj.highlight.desc+'</td></tr>');
}else{
$('#table').append('<tr class="even"><td>'+obj._source.imdbid+'</td><td>'+obj._source.name+'</td><td>'+obj._source.desc+'</td></tr>');
}
});
}
$('#count').html("Aantal resultaten: "+hitcount);
});
}

Related

Write new select2 option tags to local database in express

I am using select2 in an express app to make an input box where users can select subjects from a list, and can update this list with any newly added options.
The thing I'm struggling with is that select2 runs client-side, whereas any data I use to seed my <option> tags (that I want to append new options to) is server-side.
I want users to be able to add subjects that don't exist in the original list, so that future users will be presented with newly added options (as well as the original ones)
These are the options I've considered for achieving this (in increasing desirability):
Add new <option>Subject</option> html tags for each added tag
Push new tags to an array, and seed the <option>s from this array
Seed the <option> from a json object, and update this object on tag creation
Seed the <option> from an external database (e.g. mongoose), and update this on tag creation
As far as I can see, all of these options require that my client-side code (select2-js) talks to server-side code (where my array, .json file or mongoose schema would be), and I have no idea how to go about doing this.
In my current approach I am attempting to to specify a "local" json file as my data source in my select2 call (see here). However, this doesn't seed the database with any options, so this isn't working as I expected.
I then check if each new tag exists in an array (dataBase), and add it to the database if not:
// Data to seed initial tags:
var dataBase = [
{ id: 0, text: 'Maths'},
{ id: 1, text: 'English'},
{ id: 2, text: 'Biology'},
{ id: 3, text: 'Chemistry'},
{ id: 4, text: 'Geography'}
];
$(document).ready(function() {
$('.select2-container').select2({
ajax: {
url: '../../subjects.json',
dataType: 'json',
},
width: 'style',
multiple: true,
tags: true,
createTag: function (tag) {
var isNew = false;
tag.term = tag.term.toLowerCase();
console.log(tag.term);
if(!search(tag.term, dataBase)){
if(confirm("Are you sure you want to add this tag:" + tag.term)){
dataBase.push({id:dataBase.length+1, text: tag.term});
isNew = true;
}
}
return {
id: tag.term,
text: tag.term,
isNew : isNew
};
},
tokenSeparators: [',', '.']
})
});
// Is tag in database?
function search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].text.toLowerCase() === nameKey.toLowerCase()) {
return true
}
}
return false
};
However, this approach will add the new tags to an array that is destroyed once I refresh the page, and new tags are not stored.
How can I modify this to load server-side data (json, mongoose document or anything else that is considered a best practice), and update this data with newly added options (that pass my tests)?
On your server-side, you can have an api that maintains and returns the tag array.
If you want the array to persist even after server shutdown, you can store the tags array in a database.
Server side:
let dataBase = [
{ id: 0, text: 'Maths'},
{ id: 1, text: 'English'},
{ id: 2, text: 'Biology'},
{ id: 3, text: 'Chemistry'},
{ id: 4, text: 'Geography'}
];
//Assuming you have a nodejs-express backend
app.get('/tags', (req,res) => {
res.status(200).send({tags: dataBase});
} );
Client Side:
$(document).ready(function() {
dataBase=[];
$.get("YOUR_SERVER_ADDRESS/tags", function(data, status){
console.log("Data: " + data + "\nStatus: " + status);
dataBase = data;
});
$('.select2-container').select2({
data: dataBase,
placeholder: 'Start typing to add subjects...',
width: 'style',
multiple: true,
tags: true,
createTag: function (tag) {
var isNew = false;
tag.term = tag.term.toLowerCase();
console.log(tag.term);
if(!search(tag.term, dataBase)){
if(confirm("Are you sure you want to add this tag:" + tag.term)){
dataBase.push({id:dataBase.length+1, text: tag.term});
isNew = true;
//Update the tags array server side through a post request
}
}
return {
id: tag.term,
text: tag.term,
isNew : isNew
};
},
tokenSeparators: [',', '.']
})
});
// Is tag in database?
function search(nameKey, myArray){
for (var i=0; i < myArray.length; i++) {
if (myArray[i].text.toLowerCase() === nameKey.toLowerCase()) {
return true
}
}
return false
};
You can use select2:select and select2:unselect event for this.
var dataBase = [{
id: 0,
text: 'Maths'
},
{
id: 1,
text: 'English'
},
{
id: 2,
text: 'Biology'
},
{
id: 3,
text: 'Chemistry'
},
{
id: 4,
text: 'Geography'
}
];
$(document).ready(function() {
$('.select2-container').select2({
data: dataBase,
placeholder: 'Start typing to add subjects...',
width: 'style',
multiple: true,
tags: true,
createTag: function(tag) {
return {
id: tag.term,
text: tag.term,
isNew: true
};
},
tokenSeparators: [',', '.']
})
$(document).on("select2:select select2:unselect", '.select2-container', function(e) {
var allSelected = $('.select2-container').val();
console.log('All selected ' + allSelected);
var lastModified = e.params.data.id;
console.log('Last Modified ' + lastModified);
var dbIdArray = dataBase.map((i) => i.id.toString());
var allTagged = $('.select2-container').val().filter((i) => !(dbIdArray.indexOf(i) > -1))
console.log('All Tagged ' + allTagged);
});
});
.select2-container {
width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.6-rc.0/css/select2.min.css" rel="stylesheet" />
<select class="select2-container"></select>
Here's what I've ended up with (thanks to both answers):
1. Set up a Mongoose DB to hold subjects:
models/subjects.js
var mongoose = require("mongoose");
var SubjectSchema = new mongoose.Schema({
subject: { type: String },
});
module.exports = mongoose.model("Subjects", SubjectSchema);
2. Set up api routes in node js express backend:
routes/api.js
var express = require("express");
var router = express.Router();
var Subjects = require("../models/subjects");
// GET route for all subjects in db
router.get("/api/subjects/all", function(req, res){
Subjects.find().lean().exec(function (err, subjects) {
return res.send(JSON.stringify(subjects));
})
});
// POST route for each added subject tag
router.post("/api/subjects/save", function(req, res){
var newSubject = {};
newSubject.subject = req.body.subject;
console.log("Updating db with:" + newSubject);
var query = {subject: req.body.subject};
var options = { upsert: true, new: true, setDefaultsOnInsert: true };
// Find the document
Subjects.findOneAndUpdate(query, options, function(error, subject) {
if (error) return;
console.log("Updated db enry: " + subject);
});
return res.send(newSubject);
});
3. Set up select2 input field:
public/js/select2.js
var dataBase=[];
$(document).ready(function() {
// Get all subjects from api (populated in step 2) and push to dataBase array
$.getJSON('/api/subjects/all')
.done(function(response) {
$.each(response, function(i, subject){
dataBase.push({id: subject._id, text: subject.subject});
})
console.log("dataBase: " + dataBase);
})
.fail(function(err){
console.log("$.getJSON('/api/subjects/all') failed")
})
// Get data from api, and on 'selecting' a subject (.on("select2:select"), check if it's in the dataBase. If it is, or the user confirms they want to add it to the database, send it to POST route, and save it to our Subjects db.
$('.select2-container')
.select2({
ajax: {
url : "/api/subjects/all",
dataType: 'json',
processResults: function (data) {
return {
results: $.map(data, function(obj) {
return { id: obj._id, text: obj.subject };
})
};
}
},
placeholder: 'Start typing to add subjects...',
width: 'style',
maximumSelectionLength: 5,
multiple: true,
createTag: function(tag) {
return {
id: tag.term,
text: tag.term.toLowerCase(),
isNew : true
};
},
tags: true,
tokenSeparators: [',', '.']
})
.on("select2:select", function(e) {
if(addSubject(dataBase, e.params.data.text)){
console.log(e.params.data.text + " has been approved for POST");
ajaxPost(e.params.data.text)
} else {
console.log(e.params.data.text + " has been rejected");
var tags = $('#selectSubject select').val();
var i = tags.indexOf(e.params.data.text);
console.log("Tags: " + tags);
if (i >= 0) {
tags.splice(i, 1);
console.log("post splice: " + tags);
$('select').val(tags).trigger('change.select2');
}
}
})
function ajaxPost(subject){
console.log("In ajaxPost");
var formData = {subject : subject}
$.ajax({
type : "POST",
contentType : "application/json",
url : "/api/subjects/save",
data : JSON.stringify(formData),
dataType : 'json'})
.done(console.log("Done posting " + JSON.stringify(formData)))
.fail(function(e) {
alert("Error!")
console.log("ERROR: ", e);
});
}
function addSubject(subjects, input) {
if (!input || input.length < 3) return false
var allSubjects = [];
$.each(subjects, function(i, subject){
if(subject.text) allSubjects.push(subject.text.toLowerCase())
});
console.log("Here is the entered subject: " + input);
if(allSubjects.includes(input)){
console.log(input + " already exists")
return true
}
if(confirm("Are you sure you want to add this new subject " + input + "?")){
console.log(input + " is going to be added to the database");
return true
}
console.log(input + " will NOT to added to the database");
return false
}
});
This works, but I would love to hear feedback on this approach!

Expanding a fancyTree via lazy load

I have set up my fancytree to open via lazy loading, and it works very nicely.
$("#tree").fancytree({
selectMode: 1, quicksearch:true, minExpandLevel:2,
autoScroll: true,
source: [{
title: "Root",
key: "1",
lazy: true,
folder: true
}],
lazyLoad: function(event, data) {
var node = data.node;
data.result = {
url: "getTreeData.jsp?parent=" + node.key,
data: {
mode: "children",
parent: node.key
},
cache: false
};
}
});
However, if a user has previously selected a point on the tree, I would like the tree to open to that point.
I have a variable called hierarchy which looks like "1/5/10/11/200" and holds the sequence of keys to that certain point.
The following will not work:
$("#tree").fancytree("getTree").getNodeByKey("1").setExpanded();
$("#tree").fancytree("getTree").getNodeByKey("5").setExpanded();
$("#tree").fancytree("getTree").getNodeByKey("10").setExpanded();
$("#tree").fancytree("getTree").getNodeByKey("11").setExpanded();
$("#tree").fancytree("getTree").getNodeByKey("200").setExpanded();
The reason why it will not work, apparently, is because there needs to be some delay between one statement and the next.
The following code works, however it is in my mind messy:
function openNode(item) {
$("#tree").fancytree("getTree").getNodeByKey(String(item)).setExpanded();
}
function expandTree(hierarchy) {
var i=0;
hierarchy.split("/").forEach(function (item) {
if (item!="") {
i++;
window.setTimeout(openNode, i*100,item);
}
});
Is there any neater way of opening to a specific point on the tree?
The following code seems to do the trick.
It was adapted from
http://wwwendt.de/tech/fancytree/doc/jsdoc/Fancytree.html#loadKeyPath
function expandTree(hierarchy) {
$('#tree').fancytree("getTree").loadKeyPath(hierarchy).progress(function(data) {
if (data.status === "loaded") {
console.log("loaded intermediate node " + data.node);
$('#tree').fancytree("getTree").activateKey(data.node.key);
} else if (data.status === "ok") {}
}).done(function() {});
}

Having trouble retrieving custom attribute from HTML Option. Getting back [object Object] instead

I've been struggling with this one all day. I'm making an ajax call to a hard coded JSON file and attempting to store some of the contents into option tags using custom attributes. When I try to retrieve the data that I'm storing in the custom attribute, I keep getting [object Object]. If I try to JSON.stringify() that, I just get "[object Object]" (same as before, except wrapped in double quotes).
Some advice would be very helpful.
This is my currently empty select tag in HTML:
<select id="attackList"></select>
Actual JSON file:
{"attacks":[
{
"attackName":"Jab (1)",
"attackData":{"hitFrame":"9", "faf":"26", "damage":"1.5"}
},
{
"attackName":"Jab (3)",
"attackData":{"hitFrame":"11", "faf":"34", "damage":"2.7"}
},
{
"attackName":"Dash Attack (Early)",
"attackData":{"hitFrame":"15", "faf":"47", "damage":"10"}
},
{
"attackName":"Dash Attack (Late)",
"attackData":{"hitFrame":"21", "faf":"47", "damage":"8"}
},
{
"attackName":"Forward Tilt (1)",
"attackData":{"hitFrame":"12", "faf":"32", "damage":"3.5"}
},
{
"attackName":"Forward Tilt (3)",
"attackData":{"hitFrame":"14", "faf":"43", "damage":"8.5"}
},
{
"attackName":"Up Tilt(1, Early)",
"attackData":{"hitFrame":"7", "faf":"27", "damage":"5"}
},
{
"attackName":"Up Tilt (1, Late)",
"attackData":{"hitFrame":"9", "faf":"27", "damage":"2"}
},
{
"attackName":"Up Tilt (2)",
"attackData":{"hitFrame":"11", "faf":"27", "damage":"6"}
},
{
"attackName":"Down Tilt (Weak)",
"attackData":{"hitFrame":"7", "faf":"26", "damage":"6"}
},
{
"attackName":"Down Tilt (Strong)",
"attackData":{"hitFrame":"7", "faf":"26", "damage":"7"}
},
{
"attackName":"Forward Smash (Weak)",
"attackData":{"hitFrame":"19", "faf":"68", "damage":"14"}
},
{
"attackName":"Forward Smash (Strong)",
"attackData":{"hitFrame":"19", "faf":"68", "damage":"16"}
},
{
"attackName":"Up Smash (Early)",
"attackData":{"hitFrame":"18", "faf":"65", "damage":"17"}
},
{
"attackName":"Up Smash (Mid)",
"attackData":{"hitFrame":"20", "faf":"65", "damage":"16"}
},
{
"attackName":"Up Smash (Late)",
"attackData":{"hitFrame":"22", "faf":"65", "damage":"15"}
},
{
"attackName":"Up Smash (Late)",
"attackData":{"hitFrame":"22", "faf":"65", "damage":"15"}
},
{
"attackName":"Down Smash (1)",
"attackData":{"hitFrame":"20", "faf":"69", "damage":"5"}
},
{
"attackName":"Down Smash (2, Early)",
"attackData":{"hitFrame":"25", "faf":"69", "damage":"16"}
},
{
"attackName":"Down Smash (2, Late)",
"attackData":{"hitFrame":"26", "faf":"69", "damage":"15"}
}
]}
AJAX call that populates the select tag:
$.ajax({
url: attackerFileName,
dataType: 'json',
type: 'get',
cache:true,
success: function(data){
$(data.attacks).each(function(index,value){
console.log(value.attackData);
dropdownOptions.append($("<option></option>").attr("data-value", value.attackData).text(value.attackName));
});
}
});
And the JS code that attempts to retrieve the custom attribute from the currently selected option:
var selectedAttack = $("#attackList option:selected").data("value");
console.log(selectedAttack);
Anyone have any clue why I can't get the actual "attackData" contents from the JSON to come back? If I add code to log the attackData element from the JSON BEFORE its stored into the custom attribute, it comes back just fine. But after I retrieve it, [object Object] is all I get.
Thanks so much in advance to anyone who takes the time to look into this!
The html options can only take primitive values as a string representation.
When you set an option using the attr function, the string representation of the value is taken. In case it is an object, you will get back [object Object] as you are actually storing this value.
However, you can use the $.data function to set the data as an object.
Setting the data value in the following way should do the trick
$('<option></option>').data('value', value.attackData);
or as shown in the code snippet below
'use strict';
var mock = [{
name: 'Option 1',
value: {
identifier: 'option1',
value: {
hello: 'world'
}
}
}, {
name: 'Option 2',
value: {
identifier: 'option2',
value: {
world: 'hello'
}
}
}, {
name: 'Option 3',
value: {
identifier: 'option3',
value: {
sentence: 'hello world'
}
}
}];
$(function() {
setTimeout(function(data) {
// fake postback
var targetElement = $('#dropdown');
data.forEach(function(item) {
var option = $('<option></option>').data('value', item.value).text( item.name );
$(targetElement).append( option );
});
}.bind(null, mock));
$('#dropdown').on('change', function() {
var si = this.selectedIndex,
option = this.options[si],
name = option.text,
value = $.data( option, 'value' );
$('#output').html(name + '<br/>' + JSON.stringify(value));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="dropdown">
</select>
<div id="output">
</div>

Algolia template if no hits are returned

I've implemented my own Algolia PoC based of https://www.algolia.com/doc/search/auto-complete and I'm now struggling with a specific use case: how can I handle a search which does not return any hits?
Here is my code:
I've been able to identify and detect when/where no hits are returned, but I can't do anything beside just using a console.log(). I tried to get a custom return_msg but I can't call the function.
I also tried to do some tweak under suggestion: function(suggestion) but this function is never called if no hits are returned.
I also did not found any documentation about this "Templates" section on https://github.com/algolia/autocomplete.js
$('#q').autocomplete({ hint: false }, [
{
source: function(q, cb) {
index.search(q,
{ hitsPerPage: 10 },
function(error, content) {
if (error) {
cb([]);
return;
}
if (content.nbHits == 0)
{ return_msg = '<h5> Sorry, no result </h5>';
// DO something here
console.log(return_msg);
// console.log return "Sorry, no result"
}
cb(content.hits, content);
});
},
displayKey: 'game',
templates: {
suggestion: function(suggestion) {
return_msg = '<h5> '+ suggestion.MY_ATTRIBUTE + '</h5>'
return return_msg;
}
}
}
]).on('autocomplete:selected', function(event, suggestion, dataset) {
window.location = (suggestion.url);
});
Any pointers would be greatly appreciated =)
Using the templates option of your dataset you can specify the template to use when there are no results:
source: autocomplete.sources.hits(indexObj, { hitsPerPage: 2 }),
templates: {
suggestion: // ...
header: // ...
footer: // ...
empty: function(options) {
return '<div>My empty message</div>';
}
}
Full documentation here.

FuelUX datagrid not loading (using example)

I'm new to FuelUX so I was trying to get this to work, based on the example provided:
require(['jquery','data.js', 'datasource.js', 'fuelux/all'], function ($, sampleData, StaticDataSource) {
var dataSource = new StaticDataSource({
columns: [{property:"memberid",label:"LidId",sortable:true},{property:"name",label:"Naam",sortable:true},{property:"age",label:"Leeftijd",sortable:true}],
data: sampleData.memberdata,
delay: 250
});
$('#MyGrid').datagrid({
dataSource: dataSource,
stretchHeight: true
});
});
});
With this as the data:
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(factory);
} else {
root.sampleData = factory();
}
}(this, function () {
return {
"memberdata": [{
"memberid": 103,
"name": "Laurens Natzijl",
"age": "25"
}, {
"memberid": 104,
"name": "Sandra Snoek",
"age": "25"
}, {
"memberid": 105,
"name": "Jacob Kort",
"age": "25"
}, {
"memberid": 106,
"name": "Erik Blokker",
"age": "25"
}, {
"memberid": 107,
"name": "Jacco Ruigewaard",
"age":"25"
},{ /* etc */ }]
}
}));
I've got no console errors, no missing includes. Everthing works just fine - it even looks like it's loading. Except nothing shows up in the datagrid but '0 items'.
Any suggestions? I think I did everything the example provided...
EDIT: 14:33 (Amsterdam)
There seems to be a difference when I put this in console:
My page:
require(['jquery','data.js','datasource.js', 'fuelux/all'], function ($, sampleData, StaticDataSource) {
var dataSource = new StaticDataSource({
columns: [{property:"memberid",label:"LidId",sortable:true},{property:"name",label:"Naam",sortable:true},{property:"age",label:"Leeftijd",sortable:true}],
data: sampleData.memberdata,
delay: 250
});
console.debug(dataSource);
});
1st row in console:
function localRequire(deps, callback, errback) { /* etc */ }
2nd row in console:
StaticDataSource {_formatter: undefined, _columns: Array[3], _delay: 250, _data: Array[25], columns: function…}
FuelUX Example:
require(['jquery', 'sample/data', 'sample/datasource', 'sample/datasourceTree', 'fuelux/all'], function ($, sampleData, StaticDataSource, DataSourceTree) {
var dataSource = new StaticDataSource({
columns: [{property: 'toponymName',label: 'Name',sortable: true}, {property: 'countrycode',label: 'Country',sortable: true}, {property: 'population',label: 'Population',sortable: true}, {property: 'fcodeName',label: 'Type',sortable: true}],
data: sampleData.geonames,
delay: 250
});
console.debug(dataSource);
});
1st row in console:
StaticDataSource {_formatter: undefined, _columns: Array[4], _delay: 250, _data: Array[146], columns: function…}
2nd row in console:
function (deps, callback, errback, relMap) { /* etc */ }
Maybe this will help you help me :)
I didn't see all of the information I needed to provide a finite answer. The real magic is the datasource.js file (which you had not provided).
I thought an easier way of demonstrating all the necessary pieces would be to put together a JSFiddle showing your data in use and all the pieces that were necessary.
Link to JSFiddle of Fuel UX Datagrid sample with your data
Adam Alexander, the author of the tool, also has written a valuable example of using the dataGrid DailyJS Fuel UX DataGrid
// DataSource Constructor
var StaticDataSource = function( options ) {
this._columns = options.columns;
this._formatter = options.formatter;
this._data = options.data;
this._delay = options.delay;
};
StaticDataSource.prototype = {
columns: function() {
return this._columns
},
data: function( options, callback ) {
var self = this;
var data = $.extend(true, [], self._data);
// SEARCHING
if (options.search) {
data = _.filter(data, function (item) {
for (var prop in item) {
if (!item.hasOwnProperty(prop)) continue;
if (~item[prop].toString().toLowerCase().indexOf(options.search.toLowerCase())) return true;
}
return false;
});
}
var count = data.length;
// SORTING
if (options.sortProperty) {
data = _.sortBy(data, options.sortProperty);
if (options.sortDirection === 'desc') data.reverse();
}
// PAGING
var startIndex = options.pageIndex * options.pageSize;
var endIndex = startIndex + options.pageSize;
var end = (endIndex > count) ? count : endIndex;
var pages = Math.ceil(count / options.pageSize);
var page = options.pageIndex + 1;
var start = startIndex + 1;
data = data.slice(startIndex, endIndex);
if (self._formatter) self._formatter(data);
callback({ data: data, start: 0, end: 0, count: 0, pages: 0, page: 0 });
}
};
If you were to provide your markup and what your "datasource.js" file contains, I may be able to help you further.
I think the demonstration provides much information on any pieces you may not have understood.
Adding on to creatovisguru's answer:
In his JSFiddle example, pagination is broken. To fix it, change the following line:
callback({ data: data, start: start, end: end, count: count, pages: pages, page: page });
I had the exact same issue, when tried to integrate with Django. The issue I believe is on this line :
require(['jquery','data.js','datasource.js', 'fuelux/all'], function ($, sampleData, StaticDataSource) {
I was not able to specify file extension, my IDE (pycharm), would mark "red", when used "data.js", so it needs to stay without an extension, such as "sample/data"
What I end up doing to make it work, is downloading the full fuelux directory from github in /var/www/html on a plain Apache setup ( no django, to avoid URL.py issues for static files ) and everything works using their example. Here are the steps to get you started :
cd /var/www/html
git clone https://github.com/ExactTarget/fuelux.git
and you will end up with fuelux in /var/www/html/fuelux/
in your browser, navigate to : http://foo.com/fuelux/index.html ( assuming your default document root is /var/www/html )
good luck!

Categories