Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/434.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使用通用的self init函数获取数据,然后分别处理回调(complete)?_Javascript_Jquery_Ajax_Get_Prototype - Fatal编程技术网

Javascript 如何使用通用的self init函数获取数据,然后分别处理回调(complete)?

Javascript 如何使用通用的self init函数获取数据,然后分别处理回调(complete)?,javascript,jquery,ajax,get,prototype,Javascript,Jquery,Ajax,Get,Prototype,我有一个名为contentFetcher的组件,负责从API获取内容: 'use strict'; import $ from 'jquery'; export default ContentFetch; /* `element` is the element where you'd like to render the complete callback `urlFeed` is the URL API `onComplete` is the callback (func

我有一个名为
contentFetcher
的组件,负责从API获取内容:

'use strict';
import $ from 'jquery';
export default ContentFetch;

/*
  `element` is the element where you'd like to render the complete 
   callback
  `urlFeed` is the URL API
  `onComplete` is the callback (function)
*/
function ContentFetch(element, urlFeed, onComplete) {
    $.get({
        url: urlFeed,
        crossDomain: true,
        dataType: 'html',
        success: (data, responseText, jqXHR) => {
            ContentFetch.showData(element, data);
            if (jqXHR.status == 204) {
                ContentFetch.hideWidget(element);
            }
        },
        error: () => {
            ContentFetch.hideWidget(element);
        },
        complete: onComplete
    });
}

ContentFetch.showData = function(element, data) {
    $(element).html(data);
};

ContentFetch.hideWidget = function(element) {
    $(element).addClass('is-hidden');
};
此时,我通过导入
ContentFetch
使用它,并通过调用:
contentFetch(元素,component.urlFeed,handleComplete)

PS:handleComplete的示例是:
const handleComplete=function(){console.log('callback on complete yay');}

这是可行的,但我想将其重构为更通用的,
ContentFetcher
将只获取数据,然后单独处理回调。我想让
ContentFetcher
成为一个自初始化组件。
有人能给我一个好的策略吗?

你说的“自我初始化组件”是什么意思?您是否可以提供一些其他示例组件,它们是“self init”?在将具有默认选择器的所有元素转换为组件时进行自我初始化,例如:
$(组件选择器)。每个(函数(索引,元素){return new ContentFetch(元素);})仍然对您想要的内容感到有点困惑。你能自己先试试重构吗?如果完成了一些重构工作,并提出了一些特定的问题,则更容易理解您的意图。