对象获取相同的api端点

时间:2018-04-10 09:47:01

标签: javascript

我正在我网站的每个页面上创建此对象的两个实例。当它加载时,它 对数据进行对/cities.json的获取调用,然后将其存储在会话存储中。

下次对象 创建(在另一个页面上),它在调用api端点之前检查会话存储,以防止 不必要的数据请求。但是,当首次创建对象时,它会对/cities.json api进行两次调用 - 因为存在两个实例typehead。

除了将调用移动到对象创建之外,我不想这样做,因为其他对象也需要这个相同的api 端点,我想找到一个适用于每个模式的模式。

Index.js

import Typeahead from '../typeahead'

    var typeaheadElements = [].slice.call(document.getElementsByClassName('typeahead'));
    if (typeaheadElements.length) {
      typeaheadElements.map(function (element) { 
        new Typeahead(element);  
      });  
    }

Typeahead.js

import fetchPromise from '../utilities/fetchSetStorage.js';

function Typeahead(element) {
  init.call(this);

  function init() {
    var input = element.getElementsByTagName('input')[0];
    if (input) {

      let citiesData = fetchPromise('./cities.json', 'citiesJson');
      Promise.all([citiesData]).then(function(values) {
        items = values[0];
        element.getElementsByTagName('input')[0].removeAttribute('disabled');
      });

      input.addEventListener('input', handleChange.bind(this));
      element.addEventListener('keydown', handleKeyDown.bind(this));
      element.addEventListener('click', handleElementClick.bind(this));
      document.addEventListener('click', handleDocumentClick.bind(this));
    }
  }
}

fetchSetStorage.js

export default function fetchPromise(url, storageKey) {
  if(sessionStorage.getItem(storageKey)) {
    let storageKeyVal = JSON.parse(sessionStorage.getItem(storageKey));
    return storageKeyVal;
  } 

  return fetch(url)
    .then(function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }
      return response;
    })
    .then(response => response.json())
    .then(response => {
      sessionStorage.setItem(storageKey, JSON.stringify(response))
      return response;
    })
    .catch(function(err) {
      console.log('Fetch Error :-S', err);
    })
}

function Typeahead(element) {
  init.call(this);

  function init() {
    var input = true;
    if (input) {
      console.log('input')
      let citiesData = fetchPromise('/echo/json/', 'citiesJson');
      Promise.all([citiesData]).then(function(values) {
        items = values[0];
        console.log(values);
      });
    }
  }
}

function fetchPromise(url, storageKey) {
  if (sessionStorage.getItem(storageKey)) {
    let storageKeyVal = JSON.parse(sessionStorage.getItem(storageKey));
    return storageKeyVal;
  }

  return fetch(url)
    .then(function(response) {
      if (response.status !== 200) {
        console.log('Looks like there was a problem. Status Code: ' +
          response.status);
        return;
      }
      return response;
    })
    .then(response => response.json())
    .then(response => {
      sessionStorage.setItem(storageKey, JSON.stringify(response))
      return response;
    })
    .catch(function(err) {
      console.log('Fetch Error :-S', err);
    })
}

var typeaheadElements = [].slice.call(document.getElementsByClassName('typeahead'));
if (typeaheadElements.length) {
  console.log('typeaheadfound');
  typeaheadElements.map(function(element) {
    new Typeahead(element);
  });
}
<div class="typeahead">
  Typeahead
</div>

<div class="typeahead">
  Typeahead
</div>

1 个答案:

答案 0 :(得分:0)

我的“肮脏”解决方案:

<强> Typeahead.js

import fetchPromise from '../utilities/fetchSetStorage.js';

let isFetched = false;

function Typeahead(element) {
  init.call(this);

  function init() {
    var input = element.getElementsByTagName('input')[0];
    if (input && !isFetched) {
      isFetched = true;
      let citiesData = fetchPromise('./cities.json', 'citiesJson');
      Promise.all([citiesData]).then(function(values) {
        items = values[0];
        element.getElementsByTagName('input')[0].removeAttribute('disabled');
      });

      input.addEventListener('input', handleChange.bind(this));
      element.addEventListener('keydown', handleKeyDown.bind(this));
      element.addEventListener('click', handleElementClick.bind(this));
      document.addEventListener('click', handleDocumentClick.bind(this));
    }
  }
}