function getData(url, callback) {
var RESPONSES = {
'/countries': [
{name: 'Cameroon', continent: 'Africa'},
{name :'Fiji Islands', continent: 'Oceania'},
{name: 'Guatemala', continent: 'North America'},
{name: 'Japan', continent: 'Asia'},
{name: 'Yugoslavia', continent: 'Europe'},
{name: 'Tanzania', continent: 'Africa'}
],
'/cities': [
{name: 'Bamenda', country: 'Cameroon'},
{name: 'Suva', country: 'Fiji Islands'},
{name: 'Quetzaltenango', country: 'Guatemala'},
{name: 'Osaka', country: 'Japan'},
{name: 'Subotica', country: 'Yugoslavia'},
{name: 'Zanzibar', country: 'Tanzania'},
],
'/populations': [
{count: 138000, name: 'Bamenda'},
{count: 77366, name: 'Suva'},
{count: 90801, name: 'Quetzaltenango'},
{count: 2595674, name: 'Osaka'},
{count: 100386, name: 'Subotica'},
{count: 157634, name: 'Zanzibar'}
]
};
setTimeout(function () {
var result = RESPONSES[url];
if (!result) {
return callback('Unknown url');
}
callback(null, result);
}, Math.round(Math.random * 1000));
}
/**
* Ваши изменения ниже
*/
var requests = ['/countries', '/cities', '/populations'];
var responses = {}; //, counter=0;
for (var i = 0; i < 3; i++) {
var _request = requests[i];
var callback = function(request){
return function (error, result) {
responses[request] = result;
var i, j;
if (Object.keys(responses).length == 3) { //or counter++==3
var c = [], cc = [], p = 0;
for (i = 0; i < responses['/countries'].length; i++) {
if (responses['/countries'][i].continent === 'Africa') {
c.push(responses['/countries'][i].name);
}
}
for (i = 0; i < responses['/cities'].length; i++) {
for (j = 0; j < c.length; j++) {
if (responses['/cities'][i].country === c[j]) {
cc.push(responses['/cities'][i].name);
}
}
}
for (i = 0; i < responses['/populations'].length; i++) {
for (j = 0; j < cc.length; j++) {
if (responses['/populations'][i].name === cc[j]) {
p += responses['/populations'][i].count;
}
}
}
console.log('Total population in African cities: ' + p);
}
}
}(_request);
getData(_request, callback);
}
var requests = ['/countries', '/cities', '/populations'];
var responses = {};
function load(request){
return new Promise(function(resolve,reject){
getData(request,function(error, result){
if(!error){
resolve(result);
}else{
reject (error);
}
})
});
}
function getPopulation(state){
return Promise.all(requests.map(function(request){
return load(request);
})).then(function(data){
//console.log(arguments);
var countries=data[0],
cities=data[1],
populations=data[2],
result;
console.log(countries,cities,populations);
//calc here for state
return result;
},function(error){
console.warn("Data error",error);
});
}
getPopulation("Africa").then(console.log);
function loadScript(src,_timeout) {
return new Promise(function(resolve, reject){
if(!src){
reject(new TypeError("filename is missing"));
return;
}
var script=document.createElement("script"),
timer,
head=document.getElementsByTagName("head")[0];
head.appendChild(script);
function leanup(){
clearTimeout(timer);
timer=null;
script.onerror=script.onreadystatechange=script.onload=null;
}
function onload(){
leanup();
if(!script.onreadystatechange||(script.readyState&&script.readyState=="complete")){
resolve(script);
}
}
script.onerror=function(error){
leanup();
head.removeChild(script);
script=null;
reject(new Error("network"));
};
if (script.onreadystatechange === undefined) {
script.onload = onload;
} else {
script.onreadystatechange = onload;
}
timer=setTimeout(script.onerror,_timeout||30000);
script.setAttribute("type", "text/javascript");
script.setAttribute("src", src);
});
}
function loadCSS(src, _timeout) {
var css = document.createElement('link'), c = 1000;
document.getElementsByTagName('head')[0].appendChild(css);
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
return new Promise(function(resolve, reject){
var c=(_timeout||10)*100;
if(src) {
css.onerror = function (error) {
if(timer)clearInterval(timer);
timer = null;
reject(new Error("network"));
};
var sheet, cssRules, timer;
if ('sheet' in css) {
sheet = 'sheet';
cssRules = 'cssRules';
}
else {
sheet = 'styleSheet';
cssRules = 'rules';
}
timer = setInterval(function(){
try {
if (css[sheet] && css[sheet][cssRules].length) {
clearInterval(timer);
timer = null;
resolve(css);
return;
}
}catch(e){}
if(c--<0){
clearInterval(timer);
timer = null;
reject(new Error("timeout"));
}
}, 10);
css.setAttribute("href", src);
}else{
reject(new TypeError("filename is missing"));
}
});
}
loadScript("/engine/classes/js/jquery.pickmeup.min.js").then(function(){
console.log("js ready");
},function(error){
console.log(error);
})
loadCSS("/engine/classes/css/pickmeup.min.css").then(function(){
console.log("css ready");
},function(error){
console.log(error);
})
var data = [
'08-10-2011',
'08-04-2007',
'03-11-2008',
'03-03-2008',
'03-14-2008',
'03-28-2005',
'03-20-2005'
];
function decodeDate(arr) {
var i, len = data.length,
obj = {},
date,
year,
month;
for (i = 0; i < len; i++) {
date=arr[i].split("-");
if(!obj[year=date[2]])obj[year]={};
if(!obj[year][month=date[0]]){
obj[year][month]=[date[1]];
}else{
obj[year][month].push(date[1]);
}
}
return obj;
}
console.log(decodeDate(data));
function decodePath(url){
var parts=(url+"").split("?",2),
path=(parts[0]+'').split("/"),
query=(parts[1]+'').split("&"),
params={};
query.forEach(function(value){
var group=value.split("=");
params[group[0]]=group[1];
});
return {
path:path,
params:params
};
}
console.log(decodePath("param1/param2/?name1=value1&name2=value2"));
/*
Вернет
params: Object { name1="value1", name2="value2"}
path : ["param1", "param2", ""]
*/
jQuery("#wc_pr_incr_buy").html( "<a href='#'>Оформить покупку</a>" ).click(function(event){
event.stopPropagation(); //отмена перехода
var button= prod.find(".add_to_cart_button"),
id=button.attr("data-product_id"), //получаем id продукта
sku=button.attr("data-product_sku");
jQuery.ajax({
url:"/wp-admin/admin-ajax.php",
data:"action=woocommerce_add_to_cart&product_id="+id+"&product_sku="+sku+"&quantity=1",
type:"POST",
success: function (data, textStatus) { // вешаем обработчик на функцию success
window.location.href="/checkout";
}
});
});
в ссылке на оформление можно написать вместо <a href='#'>Оформить покупку</a> <a href='/magazin?add-to-cart="+prod+"'>Оформить покупку</a>" ради просто "нормальности ссылки" - этот url не учитывается при клике
<select onchange="updatePrice(this)">
<option data-price='10000'>Angelina Jolie</option>
<option data-price='20000'>Jessica Alba</option>
<option data-price='30000'>Mila Kunis</option>
</select>
function updatePrice(select){
var selected=select.options[select.selectedIndex],
price=selected.getAttribute("data-price");
confirm("Order "+select.value+" for "+price+"$ per hour?");
}
var obj = {
"0":["2","2","2","2"],
"1":["2","0"],
"28":["0","0","0","0"],
"29":["0","2"],
"30":{"3":"2","0":"2","14":"2","6":"1"},
"-2":{"8":"2","2":"1","3":"1"},
"36":{"27":"2","15":"1","16":"1"},
"-83":{"67":"2"},
"194":{"214":"2"},
"178":{"192":"2"},
"127":{"145":"2"},
"55":{"147":"2"},
"47":{"21":"1"},
"40":{"19":"1"},
"37":{"19":"1"},
"65":{"17":"1"}};
var arr=Object.keys(obj), stack=[]
arr.forEach(function(key){
var en=obj[key];
stack.push.apply(stack,Object.prototype.toString.call(en)=='[object Array]'?en:Object.keys(en));
})
var xMin=Math.min.apply(null, arr),
xMax=Math.max.apply(null, arr);
yMin=Math.min.apply(null, stack);
yMax=Math.max.apply(null, stack);
alert("["+xMin+", "+xMax+"]\n ["+yMin+","+yMax+"]");
xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', '/xhr/test.html', true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4&&xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
};
xmlhttp.send(null);
function isChild(child, parent) {
var current=child;
if(!child||!parent)return false;
if(child===parent)return true;
while (current = current.parentNode) {
if(current==parent)return true;
}
return false;
}
...
if(!isChild(event.target, popupElement)){
popup.close();
}
var name="admin"
setTimeout(function(){
alert(name);
},1000);
function sayAfter(text,delay){
setTimeout(function(){
alert(text);
},delay);
}
sayAfter("lol",1000);
(function(){
var x, y, z;
//много разного кода, много переменных, которые не нужны в глобальной области видимости
})();
<a href="/feed" data-virtual>Feed</a>
<a href="/news" data-virtual>News</a>
<a href="/users" data-virtual>Users</a>
<a href="/users">Real link</a>
document.body.addEventListener("click",function(evt){
var target=evt.target;
if(target.tagName=="A"){
if(target.hasAttribute("data-virtual")){
window.history.pushState({},target.textContent,target.href);
evt.preventDefault();
alert("Идем на "+target.href);
}
}
})
window.addEventListener("popstate",function(evt){
alert("Назад на "+window.location.href);
})