app.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. require([
  2. '/example/jquery.js',
  3. '/example/mustache.js',
  4. '../lunr.js',
  5. 'text!templates/question_view.mustache',
  6. 'text!templates/question_list.mustache',
  7. 'text!example_data.json',
  8. 'text!example_index.json'
  9. ], function (_, Mustache, lunr, questionView, questionList, data, indexDump) {
  10. var renderQuestionList = function (qs) {
  11. $("#question-list-container")
  12. .empty()
  13. .append(Mustache.to_html(questionList, {questions: qs}))
  14. }
  15. var renderQuestionView = function (question) {
  16. $("#question-view-container")
  17. .empty()
  18. .append(Mustache.to_html(questionView, question))
  19. }
  20. window.profile = function (term) {
  21. console.profile('search')
  22. idx.search(term)
  23. console.profileEnd('search')
  24. }
  25. window.search = function (term) {
  26. console.time('search')
  27. idx.search(term)
  28. console.timeEnd('search')
  29. }
  30. var indexDump = JSON.parse(indexDump)
  31. console.time('load')
  32. window.idx = lunr.Index.load(indexDump)
  33. console.timeEnd('load')
  34. var questions = JSON.parse(data).questions.map(function (raw) {
  35. return {
  36. id: raw.question_id,
  37. title: raw.title,
  38. body: raw.body,
  39. tags: raw.tags.join(' ')
  40. }
  41. })
  42. renderQuestionList(questions)
  43. renderQuestionView(questions[0])
  44. $('a.all').bind('click', function () {
  45. renderQuestionList(questions)
  46. $('input').val('')
  47. })
  48. var debounce = function (fn) {
  49. var timeout
  50. return function () {
  51. var args = Array.prototype.slice.call(arguments),
  52. ctx = this
  53. clearTimeout(timeout)
  54. timeout = setTimeout(function () {
  55. fn.apply(ctx, args)
  56. }, 100)
  57. }
  58. }
  59. $('input').bind('keyup', debounce(function () {
  60. if ($(this).val() < 2) return
  61. var query = $(this).val()
  62. var results = idx.search(query).map(function (result) {
  63. return questions.filter(function (q) { return q.id === parseInt(result.ref, 10) })[0]
  64. })
  65. renderQuestionList(results)
  66. }))
  67. $("#question-list-container").delegate('li', 'click', function () {
  68. var li = $(this)
  69. var id = li.data('question-id')
  70. renderQuestionView(questions.filter(function (question) {
  71. return (question.id == id)
  72. })[0])
  73. })
  74. })