Advertisement
Guest User

Filter.js and WP JSON API

a guest
Aug 19th, 2014
368
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var filter;
  2.  
  3. filter = {};
  4.  
  5. (function($, window) {
  6.  
  7.   'use strict';
  8.  
  9.   filter = {
  10.  
  11.     filterCount: 0,
  12.     page: '2', // Start paging form page 2
  13.  
  14.     apiLocation: '/api/get_posts/?post_type=business&count=-1',
  15.  
  16.     settings: {
  17.       filter_on_init: true,
  18.       filter_criteria: {
  19.         location: ['.js__filter-location .TYPE.any', 'taxonomy_business_location.ARRAY.slug'],
  20.         type: ['.js__filter-type .TYPE.any', 'taxonomy_business_type.ARRAY.slug']
  21.       },
  22.       search: {
  23.         input: '#filterSearch',
  24.         search_in: '.media__title, .media__body, .media__footer'
  25.       },
  26.       filter_types: {
  27.         any: function( current_value, option ){
  28.           if ( current_value === '') { return true; }
  29.           else { return current_value === option; }
  30.         }
  31.       },
  32.  
  33.       streaming: {
  34.         data_url: filter.apiLocation,
  35.         stream_after: 1,
  36.         batch_size: 10
  37.       },
  38.  
  39.       callbacks: {
  40.         after_filter: function( result ){
  41.  
  42.           // Update the map
  43.  
  44.           if ( $('body').hasClass('view-map') ) {
  45.             window.googleMap.update_markers( result );
  46.           }
  47.  
  48.           // Send custom analytics events
  49.           filter.push_analytics();
  50.  
  51.           // Don't run after the first filter (on init)
  52.           if ( filter.filterCount > 0) {
  53.  
  54.             // Change the URL and store data
  55.             filter.push_history();
  56.  
  57.             // Show the current count
  58.             filter.result_count( result );
  59.  
  60.           } else {
  61.  
  62.             // Update the sort only on the first filter
  63.             filter.result_sort();
  64.  
  65.           }
  66.  
  67.           // Add styling hooks
  68.           filter.update_styles();
  69.  
  70.           // Increment the count
  71.           filter.filterCount++;
  72.  
  73.         }
  74.       }
  75.     },
  76.  
  77.     init: function(){
  78.  
  79.       if ( $('body').hasClass('view-map') ) {
  80.         window.googleMap.init();
  81.       }
  82.  
  83.       filter.bind();
  84.       filter.create_results();
  85.  
  86.       return FilterJS( filter.get_api_data( filter.apiLocation ).posts, '#resultsList', filter.view, filter.settings );
  87.  
  88.     },
  89.  
  90.     paging: function( data ){
  91.  
  92.       // console.log(data.count);
  93.       // console.log(data.count_total);
  94.       // console.log(filter.apiLocation + '&page=' + filter.page);
  95.       //
  96.       // if (data.count <= data.totalCount) {
  97.       //
  98.       //   // Add the next page of data
  99.       //   filter.fjs.addData( filter.get_api_data( filter.apiLocation + '&page=' + filter.page ).posts );
  100.       //
  101.       //   filter.page = filter.page+1;
  102.       // }
  103.  
  104.     },
  105.  
  106.     bind: function(){
  107.  
  108.       if (Modernizr.history) {
  109.         window.onpopstate = filter.set_current_state;
  110.       }
  111.  
  112.       // Stop the form from being manually submitted
  113.       $('form').on('submit', filter.override );
  114.  
  115.       $('#filterOrder').on('change.sort', filter.result_sort );
  116.  
  117.       // $('.sub-menu').on('click.submenu', 'a', filter.override );
  118.  
  119.     },
  120.  
  121.     create_results: function(){
  122.  
  123.       // If we don't have results, create the ol
  124.       if ( !$('#resultsList ').length ) {
  125.  
  126.         $('#results').html(
  127.           '<ol id="resultsList" class="media__list"></ol>'
  128.         );
  129.  
  130.       }
  131.  
  132.       // If we do have results, remove any HTML before injeting JS templates
  133.       else {
  134.         $('#resultsList').html('');
  135.       }
  136.  
  137.     },
  138.  
  139.     update_styles: function(){
  140.  
  141.       var $first = 'first',
  142.           $last = 'last',
  143.           $visible = 'visible',
  144.           $media = $('.media');
  145.  
  146.       $('.' + $first + '-' + $visible).removeClass( $first + '-' + $visible );
  147.       $('.' + $last + '-' + $visible).removeClass( $last + '-' + $visible );
  148.  
  149.       $media.filter(':' + $visible + ':' + $first).addClass( $first + '-' + $visible );
  150.       $media.filter(':' + $visible + ':' + $last).addClass( $last + '-' + $visible );
  151.  
  152.     },
  153.  
  154.     override: function(){
  155.  
  156.       event.preventDefault();
  157.  
  158.     },
  159.  
  160.     get_url: function(){
  161.  
  162.       var location = window.location,
  163.           pathArray = location.pathname.split( '/' ),
  164.           host = location.host,
  165.           base = 'http://' + host + pathArray[0] +'/';
  166.  
  167.       return base;
  168.  
  169.     },
  170.  
  171.     is_location: function(){
  172.  
  173.       if ( filter.get_current_state().location !== '' ) { return true; }
  174.       else { return false; }
  175.  
  176.     },
  177.  
  178.     is_type: function(){
  179.  
  180.       if ( filter.get_current_state().type !== '' ) { return true; }
  181.       else { return false; }
  182.  
  183.     },
  184.  
  185.     is_search: function(){
  186.       if ( filter.get_current_state().search !== '' ) { return true; }
  187.       else { return false; }
  188.     },
  189.  
  190.     is_order: function(){
  191.       if ( filter.get_current_state().order !== '' ) { return true; }
  192.       else { return false; }
  193.     },
  194.  
  195.     get_current_state: function(){
  196.  
  197.       var $type = $('#filterType :selected'),
  198.           $location = $('#filterLocation :selected'),
  199.           $order = $('#filterOrder :selected'),
  200.           $search = $('#filterSearch'),
  201.           $view = $('#filterView');
  202.  
  203.       var current = {
  204.             type: $type.val(),
  205.             order: $order.val(),
  206.             location: $location.val(),
  207.             search: $search.val(),
  208.             typeText: $type.text(),
  209.             orderText: $order.text(),
  210.             locationText: $location.text(),
  211.             view: $view.val()
  212.           };
  213.  
  214.       return current;
  215.  
  216.     },
  217.  
  218.     set_current_state: function(){
  219.  
  220.       // Replace the current text to match the hostory state
  221.       $('#filterSearch').val( history.state.search );
  222.  
  223.       // Get all the select boxes
  224.       var $selects = $('#filterForm').find('select');
  225.  
  226.       // Iterate through the selects
  227.       $selects.each( function(){
  228.  
  229.         // Remove all selected attributes
  230.         $(this).find('option:selected').removeAttr('selected');
  231.  
  232.         // Get all the options in the selects
  233.         var $options = $(this).find('option');
  234.  
  235.         $options.each( function(){
  236.  
  237.           // Get the value
  238.           var value = $(this).val();
  239.  
  240.           // if option value matches history state value
  241.           if ( (value === history.state.location) || (value === history.state.type) || (value === history.state.order ) ) {
  242.  
  243.             // Set this as the selected option
  244.             $(this).attr('selected', 'selected');
  245.  
  246.           }
  247.  
  248.         });
  249.  
  250.       });
  251.  
  252.     },
  253.  
  254.     generate_url: function(){
  255.  
  256.       var url = filter.get_url(),
  257.           currentLocation = filter.get_current_state().location,
  258.           currentOrder = filter.get_current_state().order,
  259.           currentType = filter.get_current_state().type,
  260.           currentSearch = filter.get_current_state().search;
  261.  
  262.         url += '?s=' + currentSearch;
  263.         url += '&business_location=' + currentLocation;
  264.         url += '&business_type=' + currentType;
  265.         url += '&order=' + currentOrder;
  266.  
  267.       return url;
  268.  
  269.     },
  270.  
  271.     generate_title: function(){
  272.  
  273.       var currentLocationText = filter.get_current_state().locationText,
  274.           currentOrderText = filter.get_current_state().orderText,
  275.           currentTypeText = filter.get_current_state().typeText,
  276.           title;
  277.  
  278.       if ( filter.is_location() ) {
  279.         title = currentLocationText;
  280.       }
  281.  
  282.       else if ( filter.is_type() ) {
  283.         title = currentTypeText;
  284.       }
  285.  
  286.       else if ( filter.is_search() ) {
  287.         title = currentTypeText;
  288.       }
  289.  
  290.       else {
  291.         title = 'Filtering:' + currentTypeText + ' in ' + currentLocationText;
  292.       }
  293.  
  294.       title += ' | Local Whistler';
  295.  
  296.       return title;
  297.  
  298.     },
  299.  
  300.     push_history: function(){
  301.  
  302.       if ( Modernizr.history) {
  303.         if ( !$('#filterSearch').is(':focus') ) {
  304.           // Search does not have focus
  305.           window.history.pushState( filter.get_current_state(), filter.generate_title(), filter.generate_url() );
  306.         } else {
  307.           // Search has focus
  308.           window.history.replaceState( filter.get_current_state(), filter.generate_title(), filter.generate_url() );
  309.         }
  310.       }
  311.  
  312.     },
  313.  
  314.     push_analytics: function(){
  315.  
  316.       ga('send', 'event', 'filters', 'filter', {
  317.         'type': filter.get_current_state.typeText,
  318.         'location': filter.get_current_state.locationText,
  319.         'order': filter.get_current_state.orderText,
  320.         'search': filter.get_current_state.search,
  321.         'nonInteraction': 1
  322.       });
  323.  
  324.     },
  325.  
  326.     result_sort: function(){
  327.  
  328.       var $this = $('#filterOrder').find('option:selected');
  329.       var sortBy = '.' + $this.attr('data-sort-target');
  330.       var sortOrder = $this.attr('data-sort-order');
  331.  
  332.       console.log(sortOrder);
  333.       console.log(sortBy);
  334.       $('ol .media').tsort( sortBy, {order: sortOrder} );
  335.  
  336.       if ( filter.filterCount > 0) {
  337.         filter.push_history();
  338.       }
  339.  
  340.     },
  341.  
  342.     result_count: function( result ) {
  343.  
  344.       // Needs to match exactly with taxonomy.php
  345.       if ( !result.length ){
  346.         $('.js-result-count').text( 'No businesses found' );
  347.       }
  348.       else {
  349.         $('.js-result-count').text( 'Found: ' + result.length );
  350.       }
  351.  
  352.     },
  353.  
  354.     get_api_data: function( api_location ){
  355.  
  356.       var data;
  357.  
  358.       $.ajax({
  359.         async: false, //thats the trick
  360.         url: api_location,
  361.         dataType: 'json',
  362.         success: function( response ){
  363.            data = response;
  364.            filter.paging( data );
  365.         }
  366.       });
  367.  
  368.       return data;
  369.  
  370.     },
  371.  
  372.     get_logo: function( post ) {
  373.  
  374.       var logo = '';
  375.  
  376.       if ( post.custom_fields.logo[0] !== '' ) {
  377.  
  378.         // Iterate over each attachment in the array
  379.         $.each( post.attachments, function( $key, $value ){
  380.  
  381.           // Make sure we get the logo and not any old attachment
  382.           if ( post.custom_fields.logo[0] === $value['id'] ) {
  383.             logo =  '<a class="media__link--logo media__link--left media__thumb" href="' + post.url + '">' +
  384.                       '<img class="media__logo" src="' + post.attachments[$key].url + '" alt="' + post.title + ' Logo" />' +
  385.                     '</a>';
  386.           }
  387.  
  388.         });
  389.       }
  390.  
  391.       return logo;
  392.  
  393.     },
  394.  
  395.     get_tags: function( post ) {
  396.  
  397.       var tags = ['<ul>'];
  398.       var elem;
  399.  
  400.       if ( post.taxonomy_business_filter !== '' ) {
  401.  
  402.         // Iterate over each attachment in the array
  403.         $.each( post.taxonomy_business_filter, function(){
  404.  
  405.           // Make sure we get the logo and not any old attachment
  406.           elem = '<li class="tag__item"><a class="tag__link" href="/filter/' + this.slug + '">' + this.title + '</a>';
  407.           tags.push( elem );
  408.  
  409.         });
  410.  
  411.         elem = '</ul>';
  412.         tags.push( elem );
  413.         tags = tags.join(',') + '';
  414.         tags = tags.replace(/,/g, '');
  415.       }
  416.  
  417.       return tags;
  418.  
  419.     },
  420.  
  421.     format_date: function( dateString ) {
  422.  
  423.       var monthNames = [
  424.         'January',
  425.         'February',
  426.         'March',
  427.         'April',
  428.         'May',
  429.         'June',
  430.         'July',
  431.         'August',
  432.         'September',
  433.         'October',
  434.         'November',
  435.         'December'
  436.       ],
  437.         date = new Date( dateString ),
  438.         day = date.getDate(),
  439.         month = date.getMonth(),
  440.         year = date.getFullYear(),
  441.         monthName = monthNames[month];
  442.  
  443.       var dateArray = {
  444.         iso: date.toISOString(),
  445.         pretty: monthName + ' ' + day + ', ' + year
  446.       };
  447.  
  448.       return dateArray;
  449.  
  450.     },
  451.  
  452.     view: function( post ){
  453.  
  454.       var datetime = filter.format_date( post.date ).iso,
  455.           prettyDate = filter.format_date( post.date ).pretty;
  456.  
  457.           // Get todat
  458.           // If post is within the last week add a class of new
  459.  
  460.       if ( $('body').hasClass('view-map') ) {
  461.         window.googleMap.add_marker( post );
  462.       }
  463.  
  464.       // todo: use Mustache templates
  465.       return  '<li class="media">' +
  466.                 filter.get_logo( post ) +
  467.                   '<div class="media__body context__copy">' +
  468.                   '<h2 class="media__title">' +
  469.                     '<a class="media__link--title" href="' + post.url + '">' + post.title + '</a>' +
  470.                   '</h2>' +
  471.                   post.excerpt +
  472.                 '</div>' +
  473.                 '<time class="media__date" datetime="' + datetime + '">' + prettyDate + '</time>' +
  474.                 '<div class="media__footer">' +
  475.                   filter.get_tags( post ) +
  476.                 '</div>' +
  477.               '</li>';
  478.  
  479.     }
  480.   };
  481.  
  482.   return filter;
  483.  
  484. })(jQuery, window, document);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement