API
API (API 모듈)
API는 데이터 소스를 UI 컴포넌트에 자연스럽게 연결해 주는 동작(behavior) 모듈이에요. 요청 상태와 UI 상태를 자동으로 연결해 두면 별도의 상태 코드를 직접 관리할 필요가 없어져요.
출처: 문서
본문
Integrates Seamlessly with UI (UI와 매끄럽게 통합)
API는 데이터 소스를 UI 컴포넌트에 통합하는 과정을 매끄럽게 만들도록 설계되었어요. API 요청 상태를 UI 상태에 자동으로 연결해 줘요.
Click Me
Disabled
Preserve Templated URLs (템플릿 URL 유지)
API는 URL을 코드에서 분리해 주도록 도와줘요. 코드에 https://foo.com/get/1.0/followers.json 같은 URL 대신 get followers 같은 이름 있는 API 액션을 사용해요.
$('.button')
.api({
action: 'get followers'
})
;
$.fn.api.settings.api = {
'get followers' : '/followers/{id}?results={count}',
'create user' : '/create',
'add user' : '/add/{id}',
'search' : '/query/{query}/{/sort}'
};
HTTP 200 is Not Success (HTTP 200이 곧 성공은 아니에요)
콜백이 실행되기 전에 JSON에서 성공 조건을 먼저 파싱해서, 서버 오류를 정확히 잡아내고 프론트엔드 코드에서도 실제로 오류 조건이 발동하도록 해요.
// Responses without this status will trigger error conditions
$.fn.api.settings.successTest = function(response) {
return response.status == 'OK';
}
Translate APIs on the Fly (API를 즉석에서 변환)
제멋대로인 코드를 쓰는 서드파티 API를 사용하고 있나요? 문제없어요! API는 코드가 소비하기 전에 API의 원본 JSON 응답을 수정할 수 있게 해줘요.
Tools for Third-Party Integrations & Mocking (서드파티 통합과 목킹 도구)
response와 responseAsync 같은 새롭고 강력한 콜백을 사용하면 응답을 비동기로 목(mock) 처리하고 실제 API와 같은 콜백을 발동시킬 수 있어요.
API Example
Patrick Russel
Patrick lives in San Francisco, and studies french literature.
Follow
Creating an API (API 만들기)
API Actions (API 액션)
API는 인터페이스 요소가 조회할 수 있는 서버 액션 집합을 정의하는 방식으로 동작해요. 액션은 보통 save profile, get followers 같은 짧은 구절로 표현되며, 서버의 템플릿 URL 리소스에 대응돼요.
Required Parameters (필수 매개변수)
Uses format {variable}
Will abort the request if they cannot be found.
/* Two required variables */
$.fn.api.settings.api = {
'get followers' : '/followers/{id}?results={count}'
};
{variable} 형식을 사용하며, 값을 찾을 수 없으면 요청을 중단해요.
Optional Parameters (선택 매개변수)
Uses format {/variable}
Will not abort the request if they cannot be found.
Will be removed from the URL automatically if not available.
Any preceding slash before an optional parameter will be removed from the URL, allowing you to include them in resource paths.
/* One required, one optional variable */
$.fn.api.settings.api = {
'get followers' : '/followers/{id}/{/sort}'
};
{/variable} 형식을 사용하며, 값을 찾을 수 없어도 요청을 중단하지 않아요. 사용할 수 없으면 URL에서 자동으로 제거돼요. 선택 매개변수 앞의 슬래시도 URL에서 제거되므로 리소스 경로에 자유롭게 포함할 수 있어요.
Creating your API (API 정의하기)
엔드포인트는 애플리케이션에 한 번만 정의하는 게 좋아요. 보통 각 페이지에 포함되는 중앙 설정 파일에서 한 번에 정의해요.
/* Define API endpoints once globally */
$.fn.api.settings.api = {
'get followers' : '/followers/{id}?results={count}',
'create user' : '/create',
'add user' : '/add/{id}',
'follow user' : '/follow/{id}',
'search' : '/search/?query={value}'
};
Using URLs (URL 직접 사용)
이름 있는 API 액션은 필수가 아니에요. 요청의 URL을 직접 지정하고 같은 템플릿 문법을 사용할 수도 있어요:
$('.search.button')
.api({
url: 'https://www.google.com?q={value}'
})
;
Querying API Actions (API 액션 조회하기)
Attaching API Events (API 이벤트 연결)
다음 예제들은 웹 콘솔에서 콘솔 로그를 보면서 확인하면 가장 잘 동작해요.
Follow
// translates '/follow/{id}' to 'follow/22'
$('.follow.button')
.api({
action: 'follow user',
urlData: {
id: 22
}
})
;
Or
Follow
// also calls '/follow/22'
$('.follow.button')
.api()
;
Specifying DOM Events (DOM 이벤트 지정)
API 이벤트가 발생할 동작(action)을 바꿔야 한다면 on 매개변수를 사용할 수 있어요.
API requests for the following demos have been faked using API's response setting to avoid rate throttling from public APIs. No actual data is returned.
$('.follow.button')
.api({
action: 'follow user',
on: 'mouseenter'
})
;
Calling Immediately (즉시 호출)
API 액션이 즉시 발생하도록 하려면 on: 'now'를 사용해요. 이것은 호출된 요소에 동일한 상태 업데이트를 발동시키지만 즉시 발생해요.
// set-up API button with events
$('.follow.button')
.api({
action: 'follow user'
})
;
// do an immediate query
$('.follow.button')
.api('query')
;
Setting-up Requests (요청 설정하기)
Routing Data to URLs (URL로 데이터 라우팅)
API URL에 템플릿 변수가 포함되어 있으면 요청 중에 아래 네 가지 방법 중 하나로 대체돼요. 상속 순서로 나열돼 있어요.
All parameters used in a URL are encoded using encodeURIComponent by default, to prevent from malicious strings from affecting your query. To disable this feature you can set encodeParameters: false.
URL에 사용되는 모든 매개변수는 기본적으로 encodeURIComponent로 인코딩되어, 악성 문자열이 쿼리에 영향을 주는 것을 막아요. 이 기능을 끄려면 encodeParameters: false로 설정하면 돼요.
1. Automatically Routed URL Variables (자동 라우팅 URL 변수)
URL 액션에 지정하면 자동으로 대체되는 몇 가지 특별한 값이 있어요.
Variable
Description
Available for
text
current text value of element
All elements
value
current input value of element
Input elements
$.fn.api.settings.api.search = '/search/?query={value}';
$('.routed.example .search input')
.api({
action : 'search',
stateContext : '.ui.input'
})
;
text 변수는 요소의 현재 텍스트 값으로, 모든 요소에서 사용할 수 있어요. value 변수는 요소의 현재 입력 값으로, 입력 요소에서 사용할 수 있어요.
2. URL Variables Specified in Data Attributes (데이터 속성으로 URL 변수 지정)
URL 값을 HTML5 메타데이터 속성으로 포함할 수 있어요.
Follow Sally
Follow Jenny
// requests different URLs for each button
$('.follow.button')
.api({
action: 'follow user'
})
;
3. Settings Specified in Javascript (자바스크립트로 설정 지정)
URL 변수와 GET/POST 데이터는 자바스크립트 객체에서 실행 시점에 지정할 수 있어요.
$('.follow.button')
.api({
action : 'follow user',
method : 'POST',
// Substituted into URL
urlData: {
id: 22
},
// passed via POST
data: {
name: 'Joe Henderson'
}
})
;
4. Settings Returned from beforeSend (beforeSend가 반환하는 설정)
URL 데이터뿐 아니라 모든 실행 설정을 API 요청이 보내지기 전에 실행되는 특별한 콜백 beforeSend에서 조정할 수 있어요.
An additional callback beforeXHR lets you modify the XHR object before sending. This is different than beforeSend which is used to modify settings before send.
$('.follow.button')
.api({
action: 'follow user',
beforeSend: function(settings) {
settings.urlData = {
id: 22
};
return settings;
}
beforeXHR: function(xhr) {
// adjust XHR with additional headers
xhr.setRequestHeader ('Authorization', 'Basic XXXXXX');
return xhr;
}
})
;
추가 콜백 beforeXHR로 전송 전에 XHR 객체를 수정할 수 있어요. 이것은 전송 전에 설정을 수정하는 beforeSend와는 달라요.
Adjusting Requests (요청 조정하기)
Modifying XHR (XHR 수정)
추가 콜백 beforeXHR를 사용하면 전송 전에 XHR 객체를 수정할 수 있어요. 요청을 보내기 전에 헤더 같은 XHR 요청의 속성을 조정할 때 유용해요.
$('.follow.button')
.api({
action: 'follow user',
beforeXHR: function(xhr) {
// adjust XHR with additional headers
xhr.setRequestHeader ('Authorization', 'Basic XXXXXX');
return xhr;
}
})
;
Disabling Requests (요청 비활성화)
편의상 API는 현재 비활성화된 요소에서 요청이 발생하는 것을 자동으로 막아줘요.
Disabled
// this will never occur
$('.disabled.button')
.api({
action: 'follow user'
})
;
Cancelling Requests (요청 취소)
beforeSend는 요청 발생 조건을 확인하는 데도 사용할 수 있어요. beforeSend 콜백이 false를 반환하면 요청이 취소돼요.
// set somewhere in your code
window.isLoggedIn = false;
$('.follow.button')
.api({
action: 'follow user',
beforeSend: function(settings) {
// cancel request
if(!isLoggedIn) {
$(this).state('flash text', 'Requires Login!');
return false;
}
}
})
;
Passing Data (데이터 전달)
1. Routed Form Data (라우팅된 폼 데이터)
serializeForm 설정을 사용하거나 폼에 API 이벤트를 연결하면, API는 자동으로 가장 가까운 폼을 서버로 보내는 데이터에 포함시켜요.
serializeForm: true correctly converts structured form names like name="name[first]" into nested object literals.
Structured form data can be modified in Javascript in beforeSend.
Form data will automatically be converted to their Javascript equivalents, for instance, checkboxes will be converted to boolean values.
serializeForm: true는 name="name[first]" 같은 구조화된 폼 이름을 중첩된 객체 리터럴로 올바르게 변환해요. 구조화된 폼 데이터는 beforeSend에서 자바스크립트로 수정할 수 있고, 폼 데이터는 자바스크립트 동등 값으로 자동 변환돼요. 예를 들어 체크박스는 불리언(boolean) 값으로 변환돼요.
Structured Data Example (구조화된 데이터 예제)
아래 폼은 위에서 언급한 구조화된 폼 데이터의 장점 몇 가지를 보여줘요.
Name
Gender
Gender
Male
Female
Username
Password
Submit
$('form .submit.button')
.api({
action: 'create user',
serializeForm: true,
data: {
foo: 'baz'
},
beforeSend: function(settings) {
// form data is editable in before send
if(settings.data.username == '') {
settings.data.username = 'New User';
}
// open console to inspect object
console.log(settings.data);
return settings;
}
})
;
2. Data Routed in Javascript (자바스크립트로 라우팅된 데이터)
API 요청을 초기화할 때 서버 데이터를 직접 지정할 수 있어요.
$('.form .submit')
.api({
data: {
session: 22,
name: 'Baz'
}
})
;
3. Data Added in beforeSend (beforeSend에서 데이터 추가)
POST 또는 GET 데이터는 특별한 콜백 beforeSend를 사용해 지정할 수 있어요. 요청을 보내기 전에 데이터를 조회할 때 유용해요.
$('.form .submit')
.api({
action: 'create user',
serializeForm: true,
// arbitrary POST/GET same across all requests
data: {
session: 22
},
// modify data PER element in callback
beforeSend: function(settings) {
// cancel request if no id
if(!$(this).data('id')) {
return false;
}
settings.data.userID = $(this).data('id');
return settings;
}
})
;
Server Responses (서버 응답)
Response Callbacks (응답 콜백)
서버의 성공 응답은 onSuccess를, 실패 응답은 onFailure를 발동시켜요. onError는 XHR 오류에서만 발동하며 유효하지 않은 JSON 응답에서는 발동하지 않아요.
You can use the onResponse callback to adjust the JSON response before being parsed against a success test.
$('.follow.button')
.api({
onResponse: function(response) {
// make some adjustments to response
return response;
},
successTest: function(response) {
// test whether a JSON response is valid
return response.success || false;
},
onComplete: function(response, element, xhr) {
// always called after XHR complete
},
onSuccess: function(response, element, xhr) {
// valid response and response.success = true
},
onFailure: function(response, element, xhr) {
// request failed, or valid response but response.success = false
},
onError: function(errorMessage, element, xhr) {
// invalid response
},
onAbort: function(errorMessage, element, xhr) {
// navigated to a new page, CORS issue, or user canceled request
}
})
;
onResponse 콜백을 사용하면 성공 테스트로 파싱되기 전에 JSON 응답을 조정할 수 있어요.
Determining JSON Success (JSON 성공 판단)
API는 JSON 응답을 위한 특별한 성공 조건을 갖고 있어요. 요청의 HTTP 응답에 따라 성공/실패 콜백을 제공하는 대신, 서버의 응답이 액션이 성공했음을 알려줄 때만 요청이 성공한 것으로 간주해요. 응답은 검증 테스트 successTest에 전달되어 JSON이 유효한 응답인지 확인할 수 있어요.
$.fn.api.settings.successTest = function(response) {
if(response && response.success) {
return response.success;
}
return false;
};
Modifying Response JSON (응답 JSON 수정)
2.0 버전부터 API에는 onResponse 콜백이 포함되어 있어요. 응답이 검증되기 전에 서버의 응답을 조정할 수 있으므로, 다른 콜백이 발동하기 전에 응답을 변환할 수 있어요. API 응답을 수정할 수 없는데 응답이 필수 JSON 구조를 따라야 하는 상황에서 유용해요.
$('.ui.search')
.search({
type : 'category',
minCharacters : 3,
apiSettings : {
url : 'https://api.github.com/search/repositories?q={query}',
onResponse : function(githubResponse) {
var
response = {
results : {}
}
;
if(!githubResponse || !githubResponse.items) {
return;
}
// translate GitHub API response to work with search
$.each(githubResponse.items, function(index, item) {
var
language = item.language || 'Unknown',
maxResults = 8
;
if(index >= maxResults) {
return false;
}
// create new language category
if(response.results[language] === undefined) {
response.results[language] = {
name : language,
results : []
};
}
// add result to category
response.results[language].results.push({
title : item.name,
description : item.description,
url : item.html_url
});
});
return response;
}
}
})
;
Controlling State (상태 제어)
UI State (UI 상태)
API는 loading과 error 클래스 이름을 자동으로 추가해 줘요. API 호출이 진행됨에 따라 다른 UI 상태를 자동으로 발동시킬 수 있어요.
States Included in API Module
State
Description
API event
loading
Indicates a user needs to wait
XHR has initialized
error
Indicates an error has occurred
XHR Request returns error (does not trigger onAbort caused by page change, or if successTest fails). Stays visible for settings.errorDuration
disabled
prevents API action
none
loading 상태는 사용자가 기다려야 함을 나타내고 XHR이 초기화될 때 발동해요. error 상태는 오류가 발생했음을 나타내며, XHR 요청이 오류를 반환할 때 발동해요 (페이지 변경으로 인한 onAbort나 successTest 실패 시에는 발동하지 않아요). settings.errorDuration 동안 표시되며, disabled 상태는 API 액션을 막아요.
Text State (텍스트 상태)
API 액션을 state 모듈과 함께 초기화하면 활성화/비활성화 상태 설정이나 각 상태의 텍스트 값을 조정하는 등 UI 상태를 더 세밀하게 제어할 수 있어요:
$('.follow.button')
.api({
action: 'follow user'
})
.state({
onActivate: function() {
$(this).state('flash text');
},
text: {
inactive : 'Follow',
active : 'Followed',
deactivate : 'Unfollow',
flash : 'Added follower!'
}
})
;
States Included in State Module
State
Description
Occurs on
inactive
Default state
active
Selected state
Toggled on successful API request
activate
Explains activating action
On hover if inactive
deactivate
Explains deactivating action
On hover if active
hover
Explains interaction
On hover in all states, overrides activate/deactivate
disabled
Indicates element cannot be interacted
Triggered programmatically. Blocks API requests.
flash
Text-only state used to display a temporary message
Triggered programmatically
success
Indicates user action was a success
Triggered programmatically
warning
Indicates there was an issue with a user action
Triggered programmatically
inactive는 기본 상태이고, active는 선택된 상태로 API 요청 성공 시 토글돼요. activate는 비활성 상태에서 호버할 때 활성화 동작을, deactivate는 활성 상태에서 호버할 때 비활성화 동작을 설명해요. hover는 모든 상태에서 호버 시 발동하며 activate/deactivate를 덮어써요. disabled는 요소와 상호작용할 수 없음을 나타내며 API 요청을 막아요. flash는 임시 메시지를 보여주는 텍스트 전용 상태이고, success와 warning은 각각 사용자 동작의 성공/문제를 나타내며 모두 프로그래밍 방식으로 발동해요.
Advanced Use (고급 사용)
Fulfilling Responses (응답 처리)
2.0 버전부터 API에는 response와 responseAsync 두 매개변수가 포함되어 있어요. API 응답을 반환하는 자바스크립트 객체나 함수를 지정할 수 있어요. (이전에는 mockResponse와 mockResponseAsync였어요.)
$('.sync.mocked .button')
.api({
response: {
success: true
}
})
.state({
text: {
inactive : 'Off',
active : 'On'
}
})
;
Off
Using Custom Backends (커스텀 백엔드 사용)
responseAsync를 사용하면 API 요청을 실행하는 함수를 지정할 수 있어요. 이렇게 하면 API 요청 통합에 $.ajax 밖의 커스텀 백엔드나 래퍼를 사용할 수 있어요.
$('.async.mocked .button')
.api({
responseAsync: function(settings, callback) {
var response = {
success: true
};
// do any asynchronous task here
setTimeout(function() {
callback(response);
}, 500);
}
})
.state({
text: {
inactive : 'Off',
active : 'On'
}
})
;
Off
Behavior (동작)
모든 동작은 다음 문법으로 호출할 수 있어요:
$('.your.element')
.api('behavior name', argumentOne, argumentTwo)
;
Behavior (동작)
Description (설명)
query
Execute query using existing API settings (기존 API 설정으로 쿼리 실행)
add url data(url, data)
Adds data to existing templated url and returns full url string (기존 템플릿 URL에 데이터를 추가하고 전체 URL 문자열 반환)
get request
Gets promise for current API request (현재 API 요청의 promise 조회)
abort
Aborts current API request (현재 API 요청 중단)
reset
Removes loading and error state from element (요소에서 loading/error 상태 제거)
was cancelled
Returns whether last request was cancelled (마지막 요청이 취소되었는지 반환)
was failure
Returns whether last request was failure (마지막 요청이 실패했는지 반환)
was successful
Returns whether last request was successful (마지막 요청이 성공했는지 반환)
was complete
Returns whether last request was completed (마지막 요청이 완료되었는지 반환)
is disabled
Returns whether element is disabled (요소가 비활성인지 반환)
is mocked
Returns whether element response is mocked (요소 응답이 목 처리되었는지 반환)
is loading
Returns whether element is loading (요소가 로딩 중인지 반환)
set loading
Sets loading state to element (요소에 loading 상태 설정)
set error
Sets error state to element (요소에 error 상태 설정)
remove loading
Removes loading state to element (요소에서 loading 상태 제거)
remove error
Removes error state to element (요소에서 error 상태 제거)
get event
Gets event that API request will occur on (API 요청이 발생할 이벤트 조회)
get url encoded value(value)
Returns `encodeURIComponent` value only if value passed is not already encoded (전달된 값이 아직 인코딩되지 않은 경우에만 `encodeURIComponent` 값 반환)
read cached response(url)
Reads a locally cached response for a URL (URL에 대한 로컬 캐시 응답 읽기)
write cached response(url, response)
Writes a cached response for a URL (URL에 대한 캐시 응답 쓰기)
create cache
Creates new cache, removing all locally cached URLs (새 캐시 생성, 모든 로컬 캐시 URL 제거)
destroy
Removes API settings from the page and all events (페이지에서 API 설정과 모든 이벤트 제거)
API
AJAX
You can pass in any standard [jQuery AJAX setting](https://api.jquery.com/jquery.ajax/) like `timeout` or `contentType` to API's settings and it will be automatically passed to the request's AJAX call.
timeout이나 contentType 같은 표준 jQuery AJAX 설정을 API 설정에 전달하면 요청의 AJAX 호출에 자동으로 전달돼요.
API
Default (기본값)
Description (설명)
on
auto
When API event should occur (API 이벤트가 발생할 시점)
cache
true
Can be set to 'local' to cache successful returned AJAX responses when using a JSON API. This helps avoid server roundtrips when API endpoints will return the same results when accessed repeatedly. Setting to `false`, will add cache busting parameters to the URL. (JSON API 사용 시 'local'로 설정하면 성공적으로 반환된 AJAX 응답을 캐시할 수 있어요. 반복 접근 시 같은 결과를 반환하는 API 엔드포인트라면 서버 왕복을 줄여줘요. `false`로 설정하면 URL에 캐시 파기 매개변수를 추가해요.)
stateContext
this
UI state will be applied to this element, defaults to triggering element. (UI 상태가 적용될 요소로, 기본값은 트리거 요소예요.)
encodeParameters
true
Whether to encode parameters with `encodeURIComponent` before adding into url string (URL 문자열에 추가하기 전에 매개변수를 `encodeURIComponent`로 인코딩할지 여부)
defaultData
true
Whether to automatically include default data like {value} and {text} ({value}, {text} 같은 기본 데이터를 자동으로 포함할지 여부)
serializeForm
false
Whether to serialize closest form and include in request.If set to `'formdata'` instead of `true` the Formdata Web API is used (formdata however does not support nested named keys like `a[b][c][d]`) (가장 가까운 폼을 직렬화해 요청에 포함할지 여부. `true` 대신 `'formdata'`로 설정하면 Formdata Web API를 사용해요. 단 formdata는 `a[b][c][d]` 같은 중첩 이름 키는 지원하지 않아요.)
throttle
0
How long to wait when a request is made before triggering request, useful for rate limiting `oninput` (요청이 발생할 때까지 대기하는 시간으로, `oninput`의 속도 제한에 유용해요)
throttleFirstRequest
true
When set to false will not delay the first request made, when no others are queued (false로 설정하면 다른 요청이 대기 중이 아닐 때 첫 요청을 지연시키지 않아요)
interruptRequests
false
Whether an API request can occur while another request is still pending (다른 요청이 여전히 진행 중일 때 API 요청이 발생할 수 있는지 여부)
loadingDuration
0
Minimum duration to show loading indication (로딩 표시를 보여주는 최소 시간)
hideError
auto
The default `auto` will automatically remove error state after error duration, unless the element is a `form` (기본 `auto`는 오류 시간이 지난 후 요소가 `form`이 아닐 때 오류 상태를 자동으로 제거해요)
errorDuration
2000
Setting to `true`, will not remove error. Setting to a duration in milliseconds to show error state after request error. (`true`로 설정하면 오류를 제거하지 않아요. 밀리초 단위의 시간으로 설정하면 요청 오류 이후 오류 상태를 보여줘요.)
Request Settings (요청 설정)
Default (기본값)
Description (설명)
Possible Values (가능한 값)
action
false
Named API action for query, originally specified in $.fn.settings.api (쿼리를 위한 이름 있는 API 액션으로, 원래 `$.fn.settings.api`에 지정됨)
String or false
url
false
Templated URL for query, will override specified action (쿼리를 위한 템플릿 URL로, 지정된 액션을 덮어씀)
String or false
base
''
base URL to apply to all endpoints. Will be prepended to each given url (모든 엔드포인트에 적용할 기본 URL. 각 URL 앞에 붙음)
String
urlData
false
Variables to use for replacement (대체에 사용할 변수)
response
false
Can be set to a Javascript object which will be returned automatically instead of requesting JSON from server (서버에서 JSON을 요청하는 대신 자동으로 반환되는 자바스크립트 객체로 설정 가능)
{} or false
responseAsync(settings, callback)
false
When specified, this function can be used to retrieve content from a server and return it asynchronously instead of a standard AJAX call. The callback function should return the server response. (지정하면 표준 AJAX 호출 대신 서버에서 콘텐츠를 조회해 비동기로 반환하는 함수로 사용할 수 있어요. 콜백 함수가 서버 응답을 반환해야 해요.)
function or false
mockResponse
false
Alias of `response` (`response`의 별칭)
mockResponseAsync
false
Alias of `responseAsync` (`responseAsync`의 별칭)
rawResponse
true
If set to false, a possible given JSON Array response will be force converted into a JSON Object before being provided to the onResponse event handler, even if the datatype is json. (false로 설정하면 데이터 타입이 json이어도 주어진 JSON 배열 응답을 onResponse 이벤트 핸들러에 제공하기 전에 강제로 JSON 객체로 변환해요.)
method
get
Method for transmitting request to server (서버로 요청을 전송하는 메서드)
Any valid http method
dataType
JSON
Expected data type of response (예상 응답 데이터 타입)
xml, json, jsonp, script, html, text
data
{}
POST/GET Data to Send with Request (요청과 함께 보낼 POST/GET 데이터)
Callbacks (콜백)
Context
Description (설명)
beforeSend(settings)
initialized element
Allows modifying settings before request, or cancelling request (요청 전에 설정을 수정하거나 요청을 취소할 수 있어요)
beforeXHR(xhrObject)
Allows modifying XHR object for request (요청을 위한 XHR 객체 수정 가능)
onRequest(promise, xhr)
state context
Callback that occurs when request is made. Receives both the API success promise and the XHR request promise. (요청이 발생할 때 실행되는 콜백. API 성공 promise와 XHR 요청 promise를 모두 받아요.)
onResponse(response)
state context
Allows modifying the server's response before parsed by other callbacks to determine API event success (API 이벤트 성공을 판단하기 위해 다른 콜백이 파싱하기 전에 서버 응답을 수정할 수 있어요)
successTest(response)
Determines whether completed JSON response should be [treated as successful](#determining-json-success) (완료된 JSON 응답을 성공으로 간주할지 결정해요)
onSuccess(response, element, xhr)
state context
Callback after successful response, JSON response must pass `successTest` (성공 응답 후 콜백. JSON 응답은 `successTest`를 통과해야 해요)
onComplete(response, element, xhr)
state context
Callback on request complete regardless of conditions (조건과 무관하게 요청 완료 시 콜백)
onFailure(response, element, xhr)
state context
Callback on failed response, or JSON response that fails `successTest` (실패한 응답 또는 `successTest`를 통과하지 못한 JSON 응답 시 콜백)
onError(errorMessage, element, xhr)
state context
Callback on server error from returned status code, or XHR failure. (반환된 상태 코드에서 발생한 서버 오류 또는 XHR 실패 시 콜백)
onAbort(errorMessage, element, xhr)
state context
Callback on abort caused by user clicking a link or manually cancelling request. (사용자가 링크를 클릭하거나 요청을 수동으로 취소해 중단될 때 콜백)
Module (모듈)
이 설정들은 모든 모듈에 공통으로 적용되며, 컴포넌트가 콘텐츠를 DOM 속성에 연결하는 방식과 모듈의 디버깅 설정을 정의해요.
Default (기본값)
Description (설명)
name
API
Name used in log statements (로그 문에 사용되는 이름)
namespace
api
Event namespace. Makes sure module teardown does not effect other events attached to an element. (이벤트 네임스페이스. 모듈 해제가 요소에 연결된 다른 이벤트에 영향을 주지 않도록 해요.)
regExp
regExp : {
required: /\{\$*[A-z0-9]+\}/g,
optional: /\{\/\$*[A-z0-9]+\}/g,
}
Regular expressions used for template matching (템플릿 매칭에 사용되는 정규식)
selector
selector: {
disabled : '.disabled',
form : 'form'
}
Selectors used to find parts of a module (모듈의 일부를 찾는 데 사용되는 선택자)
className
className: {
loading : 'loading',
error : 'error'
}
Class names used to determine element state (요소 상태를 결정하는 데 사용되는 클래스 이름)
metadata
metadata: {
action : 'action',
url : 'url'
}
Metadata used to store XHR and response promise (XHR과 응답 promise를 저장하는 데 사용되는 메타데이터)
silent
false
Silences all console output including error messages, regardless of other debug settings. (다른 디버그 설정과 무관하게 오류 메시지를 포함한 모든 콘솔 출력을 조용히 해요.)
debug
false
Debug output to console (콘솔에 디버그 출력)
performance
true
Show `console.table` output with performance metrics (성능 지표와 함께 `console.table` 출력 표시)
verbose
false
Debug output includes all internal behaviors (디버그 출력에 모든 내부 동작 포함)
errors
// errors
error : {
beforeSend : 'The before send function has aborted the request',
error : 'There was an error with your request',
exitConditions : 'API Request Aborted. Exit conditions met',
JSONParse : 'JSON could not be parsed during error handling',
legacyParameters : 'You are using legacy API success callback names',
missingAction : 'API action used but no url was defined',
missingURL : 'No URL specified for API event',
noReturnedValue : 'The beforeSend callback must return a settings object, beforeSend ignored.',
parseError : 'There was an error parsing your request',
requiredParameter : 'Missing a required URL parameter: ',
statusMessage : 'Server gave an error: ',
timeout : 'Your request timed out'
}
Error messages for various conditions (여러 조건에 대한 오류 메시지)
더 알아보기 (Learn more)
API 동작은 Fomantic UI에서 서버와의 통신을 UI 상태와 연결하는 핵심 모듈이에요. 실제 프로젝트에서는 on 값이나 successTest를 바꾸는 것만으로도 요청 성공 판정 방식을 자유롭게 조정할 수 있으니, 설정 테이블을 잘 활용해 보세요.