(function () {
'use strict';
const myTab = function (selector, options) {
const setting = Object.assign({
// параметры по умолчанию
}, options || {});
// код логики табов
};
// Цепляем функцию плагина на глобальный объект
window.myTab = myTab;
}());
//> Инициализируем плагин
window.myTab('.my-tab-selector', {
active: 'active-item',
content: 'tab-item-content',
tabs: '.tabs',
onChange: function (tab) {
console.log('Таб переключили')
}
});
[
{
"title": "About my company",
"text": "Lorem ipusm ..."
}
]
<div class="about">
<h2>{{title}}</h2>
<p>{{text}}</p>
</div>
(function ($) {
'use strict';
JSONTemplate(
'https://example.com/api/about.json',
'https://example.com/templates/about.html'
).then(function (html) {
$('body').append(html);
});
function JSONTemplate(jsonLink, htmlLink) {
return promise(function (resolve, reject) {
$.when(
ajax(jsonLink, {
dataType: 'json'
}),
ajax(htmlLink, {
dataType: 'text'
})
).done(function (json, html) {
var $html = '';
json.forEach(function (item) {
$html += tag(html, item);
});
return resolve($html);
}).fail(reject);
});
}
function ajax(link, setup) {
return $.ajax($.extend(true, {}, {
method: 'GET'
}, setup || {}, {
url: link
}));
}
function tag(input, data) {
for (var tag in data) {
input = input.replace(new RegExp('\{\{' + tag + '\}\}', 'g'), data[tag]);
}
return input;
}
function promise(callback) {
var deferred = $.Deferred();
callback && callback(deferred.resolve, deferred.reject);
return deferred;
}
}(jQuery));
<body>
<div class="about">
<h2>About my company</h2>
<p>Lorem ipusm ...</p>
</div>
</body>
<div class="item">
<h2>{{title}}</h2>
<div>{{price}} <span v-show="discount">{{discount}}</span></div>
<button>{{button}}</button>
</div>
asynchronous().then(function (data) {
console.log(data); //> "test"
});
function promise(callback) {
var deferred = $.Deferred();
callback & callback(deferred.resolve, deferred.reject);
return deferred;
}
function asynchronous() {
return promise(function (resolve ,reject) {
resolve('test');
});
}
// Клик на кнопку "Отследить"
$('#trackBtn').on('click', function (event) {
event.stopPropagation();
// Ищем iframe виджета и ждем когда он загрузится
$('#YQContainer').find('iframe').on('load', function () {
// Скрываем нужный блок в iframe
$(this).contents().find('.tracklist-da').hide();
});
});
'use strict';
const axios = require('axios');
void async function main() {
const data = await Promise.all([
getCryptoList(3),
getConvertCurrency(['EUR', 'RUB', 'GBP', 'UAH'])
]);
const result = appendCryptoCourses(...data);
console.log(result);
}();
function appendCryptoCourses(list, courses) {
for (const id in list) {
const coin = list[id];
for (const currency in courses) {
const course = courses[currency];
coin.quotes[currency] = {
price: coin.quotes.USD.price * course,
volume_24h: coin.quotes.USD.volume_24h * course,
market_cap: coin.quotes.USD.market_cap * course,
percent_change_1h: coin.quotes.USD.percent_change_1h,
percent_change_24h: coin.quotes.USD.percent_change_24h,
percent_change_7d: coin.quotes.USD.percent_change_7d
};
}
}
return list;
}
async function getCryptoList(limit) {
const list = await request('https://api.coinmarketcap.com/v2/ticker/', { limit });
return list.data;
}
function getConvertCurrency(symbols) {
return request('https://min-api.cryptocompare.com/data/price', {
fsym: 'USD',
tsyms: Array.isArray(symbols) ? symbols.join(',') : symbols
});
}
function request(link, params) {
return new Promise((resolve, reject) => {
axios.get(link, { params }).then(response => resolve(response.data)).catch(reject);
});
}
{
"1": {
"id": 1,
"name": "Bitcoin",
"symbol": "BTC",
"website_slug": "bitcoin",
"rank": 1,
"circulating_supply": 17388287,
"total_supply": 17388287,
"max_supply": 21000000,
"quotes": {
"USD": {
"price": 4499.33210008,
"volume_24h": 5185812375.72332,
"market_cap": 78235677865,
"percent_change_1h": -0.45,
"percent_change_24h": -2.14,
"percent_change_7d": -19.21
},
"EUR": {
"price": 3946.8141181901756,
"volume_24h": 4548994615.984496,
"market_cap": 68628336623.178,
"percent_change_1h": -0.45,
"percent_change_24h": -2.14,
"percent_change_7d": -19.21
},
"RUB": {
"price": 304109.8566444072,
"volume_24h": 350509058475.1392,
"market_cap": 5287949466895.351,
"percent_change_1h": -0.45,
"percent_change_24h": -2.14,
"percent_change_7d": -19.21
},
"GBP": {
"price": 3515.7781030025117,
"volume_24h": 4052193790.390202,
"market_cap": 61133358683.711,
"percent_change_1h": -0.45,
"percent_change_24h": -2.14,
"percent_change_7d": -19.21
},
"UAH": {
"price": 129310.80455629919,
"volume_24h": 149040247678.2882,
"market_cap": 2248493381840.1,
"percent_change_1h": -0.45,
"percent_change_24h": -2.14,
"percent_change_7d": -19.21
}
},
"last_updated": 1542886571
},
"52": {
"id": 52,
"name": "XRP",
"symbol": "XRP",
"website_slug": "ripple",
"rank": 2,
"circulating_supply": 40327341704,
"total_supply": 99991780039,
"max_supply": 100000000000,
"quotes": {
"USD": {
"price": 0.4375704632,
"volume_24h": 579102404.360952,
"market_cap": 17646053587,
"percent_change_1h": -0.18,
"percent_change_24h": -1.61,
"percent_change_7d": -4.17
},
"EUR": {
"price": 0.38383681031904,
"volume_24h": 507988629.1054271,
"market_cap": 15479118206.5164,
"percent_change_1h": -0.18,
"percent_change_24h": -1.61,
"percent_change_7d": -4.17
},
"RUB": {
"price": 29.575387607688,
"volume_24h": 39141531510.75675,
"market_cap": 1192696761945.33,
"percent_change_1h": -0.18,
"percent_change_24h": -1.61,
"percent_change_7d": -4.17
},
"GBP": {
"price": 0.34191755994448,
"volume_24h": 452510618.7676479,
"market_cap": 13788626272.8818,
"percent_change_1h": -0.18,
"percent_change_24h": -1.61,
"percent_change_7d": -4.17
},
"UAH": {
"price": 12.575775112368,
"volume_24h": 16643403101.33376,
"market_cap": 507147580090.37994,
"percent_change_1h": -0.18,
"percent_change_24h": -1.61,
"percent_change_7d": -4.17
}
},
"last_updated": 1542886561
},
"1027": {
"id": 1027,
"name": "Ethereum",
"symbol": "ETH",
"website_slug": "ethereum",
"rank": 3,
"circulating_supply": 103354703,
"total_supply": 103354703,
"max_supply": null,
"quotes": {
"USD": {
"price": 132.472624031,
"volume_24h": 2224827274.81642,
"market_cap": 13691668675,
"percent_change_1h": -0.59,
"percent_change_24h": -2.93,
"percent_change_7d": -25.14
},
"EUR": {
"price": 116.20498579999321,
"volume_24h": 1951618485.4689636,
"market_cap": 12010331761.71,
"percent_change_1h": -0.59,
"percent_change_24h": -2.93,
"percent_change_7d": -25.14
},
"RUB": {
"price": 8953.824658255291,
"volume_24h": 150376075504.84183,
"market_cap": 925419885743.25,
"percent_change_1h": -0.59,
"percent_change_24h": -2.93,
"percent_change_7d": -25.14
},
"GBP": {
"price": 103.51410841782341,
"volume_24h": 1738480032.5415506,
"market_cap": 10698669902.645,
"percent_change_1h": -0.59,
"percent_change_24h": -2.93,
"percent_change_7d": -25.14
},
"UAH": {
"price": 3807.26321465094,
"volume_24h": 63941535878.22391,
"market_cap": 393498557719.5,
"percent_change_1h": -0.59,
"percent_change_24h": -2.93,
"percent_change_7d": -25.14
}
},
"last_updated": 1542886521
}
}
function getHashParams(link) {
return (link.match(/([^#=&]+)(=([^&]*))/g) || []).reduce(function (a, b) {
return ((a[b.slice(0, b.indexOf('='))] = b.slice(b.indexOf('=') + 1)), a);
}, {});
}
getHashParams('https://oauth.vk.com/blank.html#access_token=f95b38f461921538c204e7218e43cdc9bc40fdbf378c1adb68967c2f8b84603397f9226b7&expires_in=0&user_id=11111111')
//> {access_token: "f95b38f461921538c204e7218e43cdc9bc40fdbf378c1adb68967c2f8b84603397f9226b7", expires_in: "0", user_id: "11111111"}
$.ajax({
url: 'https://jsonplaceholder.typicode.com/users',
method: 'GET',
dataType: 'json',
success: function (data, status, jqXHR) {
console.log(jqXHR.getAllResponseHeaders());
// или jqXHR.getResponseHeader('location') (если такой header есть)
}
});
// pragma: no-cache
// content-type: application/json; charset=utf-8
// cache-control: public, max-age=14400
// expires: Mon, 19 Nov 2018 11:10:53 GMT
success: success_add_favorite
function someFunction(userID, postID) {
return $.ajax({...});
}
someFunction(a, b).done(function () {
//> Запрос прошел успешно
});
getUsers().done(function (users) {
console.log(users);
});
function promise(callback) {
var deferred = $.Deferred();
callback && callback(deferred.resolve, deferred.reject);
return deferred;
}
function getUsers() {
return promise(function (resolve, reject) {
$.ajax({
url: 'https://jsonplaceholder.typicode.com/users',
method: 'GET',
dataType: 'json',
success: function (users) {
resolve(users.filter(function (user) {
return user.id <= 5;
}));
},
error: reject
});
});
}
promiseAll([promise, promise, promise]).done(function () {
//> Все промисы завершенны успешно
});
function promiseAll(promises) {
return $.when.apply(null, promises);
}
addPost({
title: 'foo',
body: 'bar',
userId: 1
}).done(function (response) {
console.log(response); //> {title: "foo", body: "bar", userId: 1, id: 101}
});
function addPost(data) {
return $.ajax({
url: 'https://jsonplaceholder.typicode.com/posts',
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data)
});
}
request('http://api.randomuser.me/1.0/', {
results: 50,
nat: ['gb', 'us'],
inc: ['gender', 'name', 'location', 'email', 'phone', 'picture']
}).get(function (data) {
console.log(data);
}, function (error) {
console.log(error);
});
request('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
}).post(function (data) {
console.log(data);
}, function (error) {
console.log(error);
});
function request(link, params, setup) {
return {
get: function (success, error) {
return ajax(extend({}, {
url: link + (params ? '?' + param(params) : ''),
method: 'GET',
success: success || function () {},
error: error || function () {}
}, setup || {}));
},
post: function (success, error) {
return ajax(extend({}, {
url: link,
method: 'POST',
headers: {
'Content-Type': 'application/json; charset=UTF-8'
},
data: params,
success: success || function () {},
error: error || function () {}
}, setup || {}));
}
};
}
function ajax(params) {
var setting = extend({}, {
url: window.location.href,
method: 'GET',
async: true,
data: undefined,
headers: {
'Content-type': 'application/x-www-form-urlencoded; charset=UTF-8'
},
success: function (data, xhr, params) {},
error: function (error, xhr, params) {}
}, params || {});
var setHeaders = function (headers) {
for (var name in headers) {
this.setRequestHeader(name, headers[name]);
}
};
var xhr = new XMLHttpRequest();
xhr.open(setting.method, setting.url, setting.async);
setHeaders.call(xhr, setting.headers);
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
var data = (function () {
try {
return JSON.parse(this.response);
} catch (error) {
return this.response;
}
}).call(this);
setting.success(data, this, setting);
} else {
setting.error(this.status, this, setting);
}
}
}
xhr.send(setting.data ? JSON.stringify(setting.data) : null);
return xhr;
}
function param(data) {
var result = '';
for (var name in data) {
result += name + '=' + (Array.isArray(data[name]) ? data[name].join(',') : data[name]) + '&';
}
return result.slice(0, -1);
}
function extend(output) {
output = output || {};
for (var i = 1; i < arguments.length; i++) {
if (!arguments[i]) continue;
for (var key in arguments[i]) {
if (arguments[i].hasOwnProperty(key)) {
output[key] = arguments[i][key];
}
}
}
return output;
}
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://api.randomuser.me/1.0/?results=50&nat=gb,us&inc=gender,name,location,email,phone,picture', true);
xhr.onreadystatechange = function () {
if (this.readyState === 4) {
if (this.status >= 200 && this.status < 400) {
var data = JSON.parse(this.response);
console.log('Успех', data);
} else {
console.log('Ошибка', this);
}
}
}
xhr.send(null);
(function ($) {
'use strict';
void function main() {
// Пример использования promise
promise(function (resolve, reject) {
resolve('example data');
}).done(function (data) {
console.log(data); //> "example data"
});
// Пример использования promiseAll
var deferreds = [$.Deferred().resolve(1), $.Deferred().resolve(2), $.Deferred().resolve(3)];
promiseAll(deferreds).done(function () {
console.log(arguments); //> [1, 2, 3]
});
}();
function promise(callback) {
var deferred = $.Deferred();
callback && callback(deferred.resolve, deferred.reject);
return deferred;
}
function promiseAll(deferreds) {
return $.when.apply(null, deferreds);
}
}(jQuery));