1. async function은 promise 를 리턴함
2. promise는 then이나 await 로 기다림
3. await는 async 안에서만 사용한다.
Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts
Monday, October 14, 2019
Tuesday, August 9, 2016
closure usage in javascript
This is bad source all nodes are show "nodes.length-1" when you click any node
var add_the_handler = function (nodes){
var i;
for(i=0; i<nodes.length; i+=1){
nodes[i].onclick = function(e){
alert(i);
}
}
}
this is a good pattern compared to above function
var add_the_handler = function (nodes){
var i;
for(i=0; i<nodes.length; i+=1){
nodes[i].onclick = function(i){
return function(e){
alert(i)
};
}(i)
}
}
var add_the_handler = function (nodes){
var i;
for(i=0; i<nodes.length; i+=1){
nodes[i].onclick = function(e){
alert(i);
}
}
}
this is a good pattern compared to above function
var add_the_handler = function (nodes){
var i;
for(i=0; i<nodes.length; i+=1){
nodes[i].onclick = function(i){
return function(e){
alert(i)
};
}(i)
}
}
Thursday, October 29, 2015
how to make syntax highlight with javascript
I recently made a source that text javascript convert to color highlited script with html tags
below code is what I did and output
I have to do refactoring it providing multilanguage and modules.
I did it this step
1. split rows
2. parsing comments.
3. parsing String values
4. parsing variables
5. line num
https://github.com/jjhangu/colorbeauti/blob/master/test.html
If you need more detail
reply~
below code is what I did and output
I have to do refactoring it providing multilanguage and modules.
I did it this step
1. split rows
2. parsing comments.
3. parsing String values
4. parsing variables
5. line num
https://github.com/jjhangu/colorbeauti/blob/master/test.html
If you need more detail
reply~
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* 주석은 언제 작업하나?? ㅡ.ㅡ;
*/
(function(){
var MailResizer = function(){
}
MailResizer.prototype.data ={
isMode : 0, // 0 default, 1 cotent resized, 2 only image resized
isVertical : 1, // 0 false, 1 true,
imageObjectList : [] // isMode가 2인경우에만 사용
};
// 텍스트 테스트
var text = "<span id='hoho'>" + '<span id="haha">' ;
var arr = [];
var json = {};
// 이중 for문 테스트
for(var i=0; i<arr.length; i++){
// 로그 테스트
console.log("haha");
for(var i in json){
if(i.key == null){
return ;
}else if(i.key == true){
}else if(i.key == false){
} /** 1단 테스트 */
/* 주주석 */else{
console.log('주석 테스트');
}
/**
이단 테스트 function hohoho 이거는 2단 주석 테스트 입니다 )()()
*/
}
}
var hello = this.call(data);
window.MailResizer = MailResizer;
})();
Friday, September 11, 2015
bind, call, apply self-testing
name = "super-man";
var obj = { name :"mart-man", // general hello : function(){ console.log("hello : " + this.name); this.test(function(){ console.log("hello > callback : " + this.name); }); }, // bind hello_bind : function(){ console.log("hello_bind : " + this.name); this.test(function(one, two){ console.log("hello_bind > callback : " + this.name); }.bind(this)); }, test : function(callback){ callback(); } } test = function(){ console.log("out test"); } console.log(1, obj.name); console.log(2, name); console.log(3); obj.hello(); console.log(3.5); var hello_outer = obj.hello; hello_outer(); console.log(4); obj.hello_bind(); console.log(5); obj.hello.call(this); obj.hello.apply({name:'kings-man', test:function(){console.log("third test")}}); console.log('end');
If you don't understand well why this logs printed.
I suguess this website and http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/
study it~!
1 "mart-man"
2 "super-man"
3
hello : mart-man
hello > callback : super-man
3.5
hello : super-man
out test
4
hello_bind : mart-man
hello_bind > callback : mart-man
5
hello : super-man
out test
hello : kings-man
third test
end
Tuesday, July 21, 2015
페이스북 작성일 표시법 javascript source
프로젝트를 진행하다 보면 날짜를 어떻게 보여줄것인지에 대해서 많이 생각을 하게 됩니다.
어떤곳은 yyyy/mm/dd 형식으로 뿌려주는곳도 있고 dd/mm/yyyy 이런식으로 뿌려주는곳도 있는데요
머 보여주고자 하는 content의 의도에 따라 달라질거라고 생각합니다.
ex) 2015-07-22 12:00
그래서 요즘 그래도 핫한 페이스북에서는 어떠한 방식으로 보여주는지 확인해보았더니
방금전
2분
2시간
23시간
어제 오전 2시
어제 오후 8시
7월 19일 오후 11:55 (해당년에 대한 작성일)
2013년 12월 7일 (년도가 다른 날짜)
조금 더 사용자 관점과 보여주고자 하는 내용만 표시하고 '최근이 일어난 일이구나 라는' "실시간" 느낌을 받았습니다.
그래서 페이스북의 한국 시간보여주는거에 맞춰서 한번 library로 만들어봤는데 허접하지만 혹시 필요하신분 있으시면
사용하셔도 됩니다.
추가적으로 영어까지 지원할 생각인데.. 음... 헛 ㅡ.ㅡ;;
Thursday, November 6, 2014
Iscroll 4.2.5 in iput, textarea, select focus issue
I used I scroll and It was very good.
and I can't complete mobile web project because in Iscroll div I can't touch and input, textarea, select never clicked.
I find some article that somebody shared..
and all the things that I saw internet was not working.
and tried to find more and more
this is my solution
onBeforeScrollStart: function (e) {
var nodeType = e.explicitOriginalTarget ? e.explicitOriginalTarget.nodeName.toLowerCase():(e.target ? e.target.nodeName.toLowerCase():'');
if(nodeType !='select' && nodeType !='option' && nodeType !='input' && nodeType!='textarea') e.preventDefault();
},
and I can't complete mobile web project because in Iscroll div I can't touch and input, textarea, select never clicked.
I find some article that somebody shared..
and all the things that I saw internet was not working.
and tried to find more and more
this is my solution
onBeforeScrollStart: function (e) {
var nodeType = e.explicitOriginalTarget ? e.explicitOriginalTarget.nodeName.toLowerCase():(e.target ? e.target.nodeName.toLowerCase():'');
if(nodeType !='select' && nodeType !='option' && nodeType !='input' && nodeType!='textarea') e.preventDefault();
},
Iscroll 4.2.5 scroll has some how issue during scrolling
Today I tried to using I Scroll 4.2.5 for pullup to morelist and pulldown to refresh
But I was in trouble because if you scroll when it is already scrolling
page will refresh and you can see the position of scroll will be strange..
anyway I had to fix it
What i Changed code is
_start : .....
if (x != that.x || y != that.y) {
/**
* hanwha 주석 2014-11-06 더블 스크롤시 화면이 튕기는 현상 제거
*
* david
*/
//if (that.options.useTransition) that._unbind(TRNEND_EV);
//else cancelFrame(that.aniTime);
// that.steps = [];
// that._pos(x, y);
if (that.options.onScrollEnd) that.options.onScrollEnd.call(that);
}
this source is called when you are willing to scroll during scrolling.
in other word. double scrolling..
I hope to remever these things so
If you guys are faced with this problem.
remove that source.
But I was in trouble because if you scroll when it is already scrolling
page will refresh and you can see the position of scroll will be strange..
anyway I had to fix it
What i Changed code is
_start : .....
if (x != that.x || y != that.y) {
/**
* hanwha 주석 2014-11-06 더블 스크롤시 화면이 튕기는 현상 제거
*
* david
*/
//if (that.options.useTransition) that._unbind(TRNEND_EV);
//else cancelFrame(that.aniTime);
// that.steps = [];
// that._pos(x, y);
if (that.options.onScrollEnd) that.options.onScrollEnd.call(that);
}
this source is called when you are willing to scroll during scrolling.
in other word. double scrolling..
I hope to remever these things so
If you guys are faced with this problem.
remove that source.
Thursday, October 16, 2014
maintaining position in list when history back
Recently I was ordered that I have to change paging list way to infinite list, that mean I have to query with special key, not page number.
I have to think seriously, can I do this???
I searched other homepages if there are hompages that use this pattern.
Best homepage was Facebook to benchmark
Facebook show us topic in timeline and if scroll to bottom , ajax will get more data from the server.
but there are something that i should consider carefully.
what is that???
for example, i choose one topic and go backpage, list page will refresh and position I last saw will be lost.
In other word, ajax loading data dosen't save homepage last state.
To solve this problem.
I Think step.
1. in my list page, call list data from the server using ajax.
2. I scroll some position.
3. I click some data.
- I have to check scroll.x scroll.y and save in history.
4. detail page show
5. go back to list page
6. get the last scrollx, scroll.y from saved data
- ajax call againg
7. and scroll to last position.
this is what I think
I might be good to change what I'm now working on.
Test Script
1. History.js
2. Iscroll4
Wednesday, August 6, 2014
object to jsonObject and string
way to make json object
<script>
var main = new Array();
sub = new Object();
sub['key1'] = 'value1';
sub['key2'] = 'value2';
sub['key3'] = 'value3';
main[0] = sub;
sub = new Object();
sub['key1'] = 'value4';
sub['key2'] = 'value5';
sub['key3'] = 'value6';
main[1] = sub;
var jsonObject = {list:main};
alert(JSON.stringify(jsonObject));
</script>
<script>
var main = new Array();
sub = new Object();
sub['key1'] = 'value1';
sub['key2'] = 'value2';
sub['key3'] = 'value3';
main[0] = sub;
sub = new Object();
sub['key1'] = 'value4';
sub['key2'] = 'value5';
sub['key3'] = 'value6';
main[1] = sub;
var jsonObject = {list:main};
alert(JSON.stringify(jsonObject));
</script>
Thursday, July 3, 2014
javascript get parameters function
usually we want to parse data from url
this is good function ~
I'm not sure because I didn't test in all cases
so that use it before fully test
function getQueryParams (url) {
var params = {};
var parameters = (url.slice(url.indexOf('?') + 1, url.length))
.split('&');
for (var i = 0; i < parameters.length; i++) {
var param = parameters[i].split('=');
params[param[0]] = param[1];
}
return params;
}
Wednesday, July 2, 2014
This is what I parsing in html tags
today I had to parse html tag and replace ~!
document.querySelector('.mailInfo') : query if document has the tag defined mailInfo in class
table. querySelectorAll('tr') : this will return array of tr object elements
table.getAttribute('summary') : this will return value if summary attribute exist
This is Example
document.querySelector('.mailInfo') : query if document has the tag defined mailInfo in class
table. querySelectorAll('tr') : this will return array of tr object elements
table.getAttribute('summary') : this will return value if summary attribute exist
This is Example
function bigMailInit(){
// 메일 인포를 찾음...
var mailInfo = document.querySelector('.mailInfo');
var li = mailInfo.querySelectorAll('table');
// 널 체크, just in case
if(li == null || li.length ==0){
return;
}
var i=0;
var table;
// 메일 인포안에 여러개의 테이블이 있지만 대용량 테이블이 아닐수도 있어서 Summary attribute에서 체크 해야함
for(i=0; i<li.length; i++){
table = li[i];
var summary = table.getAttribute('summary');
if(summary != null){
if(summary.indexOf('대용량') >= 0 && summary.indexOf('Mass') >= 0 ){
var tbody= table.querySelectorAll('tbody');
if(tbody[0].children.length <3){
break;
}
var start =3; // tr의 3번째부터 첨부파일들이 나열
for(start; start<tbody[0].children.length; start++){
a = tbody[0].children[start].querySelectorAll('a');
var j=0;
for(j; j<a.length; j++){
a[j].href = a[j].getAttribute('href');
};
}
break;
};
};
};
}
Thursday, May 22, 2014
Using LazyLoad when you feel that you website is so so slow ~
Today I introduce Lazyload library that is made in javascript
basic pattern in html looks like below~
html
body
head
script src='download.js'
script src='hello.js'
/head
body
div
/div
/body
/html
if you call this webpage, you can see the fully loaded website after fully loading script and html tags,
that is html logic sequences, first script, second script, third script so on...
second script will be called after first script.
so if the website is huge or there are many script to be loaded.
people should wait more than they expected.
This Lazyload will make webpage fater than we think.
because we can controll to call scripts dynamically.
summary
1. dynamically loading script
2. script dependency
3. speed up when first website show
basic pattern in html looks like below~
html
body
head
script src='download.js'
script src='hello.js'
/head
body
div
/div
/body
/html
if you call this webpage, you can see the fully loaded website after fully loading script and html tags,
that is html logic sequences, first script, second script, third script so on...
second script will be called after first script.
so if the website is huge or there are many script to be loaded.
people should wait more than they expected.
This Lazyload will make webpage fater than we think.
because we can controll to call scripts dynamically.
summary
1. dynamically loading script
2. script dependency
3. speed up when first website show
Wednesday, January 8, 2014
After Ajax, This is a good pattern to make hmtl using javascirpt
Today i thought how to devide roles of html and jascript.
I learned Angular Js and this is awesome but
to use it is too hard for me ..
so i have find different way and very easy.
find sprintf and try to use it
below are sample i made
Usually i use this pattern but hard to read
Basic pattern
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id='frame'>
</div>
<script>
//ajax 파싱후 값을 가져왔다는 가정하에
var obj = [{user_seq : 'user_seq1', user_name : "홍길동", age : '22'},
{user_seq : 'user_seq2', user_name : "심청이", age : '19'},
{user_seq : 'user_seq3', user_name : "홍두깨", age : '30'}];
var i=0;
var str='';
for(i=0; i<obj.length;i ++){
str = str + '<div class="user" id="'+obj[i].user_seq+'1">'+
'<div class="name">'+obj[i].user_name +'</div>' +
'<div class="age">'+obj[i].age +'</div>';
}
document.getElementById('frame').innerHTML = str;
</script>
</body>
</html>
and changed some what different
Good pattern I think
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="sprintf.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id='frame'>
<div class="user" id="%1s">
<div class="name">%2s</div>
<div class="age">%3s</div>
</div>
</div>
<script>
//ajax 파싱후
var obj = [{user_seq : 'user_seq1', user_name : "홍길동", age : '22'},
{user_seq : 'user_seq2', user_name : "심청이", age : '19'},
{user_seq : 'user_seq3', user_name : "홍두깨", age : '30'}];
var i=0;
var str ='';
var content = document.getElementById('frame').innerHTML;;
for(i=0; i<obj.length;i ++){
str = str + sprintf(content,
obj[i].user_seq, //1
obj[i].user_name, //2
obj[i].age); //3
}
document.getElementById('frame').innerHTML = str;
</script>
</body>
</html>
Tuesday, November 12, 2013
Monday, November 11, 2013
This is basic concept of Memoization in Javascript
<!DOCTYPE>
<html>
<body>
<script>
<!-- Basic use -->
function square(num){
return num*num;
}
console.log(square(10));
function squareMemoization(num){
var result= '';
if(!squareMemoization.cache[num]){
console.log("computing value..");
result = num * num;
squareMemoization.cache[num]= result;
}
return squareMemoization.cache[num];
}
squareMemoization.cache = {};
console.log(squareMemoization(10)); //First time when we call this function. It calculates the value & cache it.
console.log(squareMemoization(10)); // Second time onwards it return the result from cache.
console.log(squareMemoization(20)); // square function will calculate again if its a new value.
var a = ["a", "b", "c"];
console.log('a.slice(1,2)');
console.log(a.slice(1,2));
console.log('a.slice(1)');
console.log(a.slice(1));
console.log(a);
console.log('Array.prototype.slice.call(a, 1)');
console.log(Array.prototype.slice.call(a, 1));
</script>
</body>
</html>
<html>
<body>
<script>
<!-- Basic use -->
function square(num){
return num*num;
}
console.log(square(10));
function squareMemoization(num){
var result= '';
if(!squareMemoization.cache[num]){
console.log("computing value..");
result = num * num;
squareMemoization.cache[num]= result;
}
return squareMemoization.cache[num];
}
squareMemoization.cache = {};
console.log(squareMemoization(10)); //First time when we call this function. It calculates the value & cache it.
console.log(squareMemoization(10)); // Second time onwards it return the result from cache.
console.log(squareMemoization(20)); // square function will calculate again if its a new value.
var a = ["a", "b", "c"];
console.log('a.slice(1,2)');
console.log(a.slice(1,2));
console.log('a.slice(1)');
console.log(a.slice(1));
console.log(a);
console.log('Array.prototype.slice.call(a, 1)');
console.log(Array.prototype.slice.call(a, 1));
</script>
</body>
</html>
Wednesday, November 6, 2013
make javascript Speed Up (2)
Asynchronous Transfer Mode getting script
function loadScript
this is sample
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Hello</p>
<script>
window.onload = loadAllScript;
function loadScript(url, callback){
var script = document.createElement("script");
script.type = "text/javascript";
console.log('loadScript');
if(script.readState){ //IE
script.onreadystatechange =function(){
if(script.readState =="loaded" || script.readyState =="complete"){
script.onreadstatechage= null;
callback();
}
};
}else{ //ELSE
script.onload=function(){
callback();
};
}
script.src=url;
document.getElementsByTagName("head")[0].appendChild(script);
}
function loadAllScript(){
console.log('loadAllScript');
loadScript("http://code.jquery.com/jquery-1.10.1.min.js", function(){
loadScript("http://s1.daumcdn.net/cfs.tistory/v/130502110925/blog/plugins/A_ShareEntryWithSNS/script/shareEntryWithSNS.js", function(){
alert();
});
});
}
</script>
</body>
</html>
function loadScript
this is sample
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<p>Hello</p>
<script>
window.onload = loadAllScript;
function loadScript(url, callback){
var script = document.createElement("script");
script.type = "text/javascript";
console.log('loadScript');
if(script.readState){ //IE
script.onreadystatechange =function(){
if(script.readState =="loaded" || script.readyState =="complete"){
script.onreadstatechage= null;
callback();
}
};
}else{ //ELSE
script.onload=function(){
callback();
};
}
script.src=url;
document.getElementsByTagName("head")[0].appendChild(script);
}
function loadAllScript(){
console.log('loadAllScript');
loadScript("http://code.jquery.com/jquery-1.10.1.min.js", function(){
loadScript("http://s1.daumcdn.net/cfs.tistory/v/130502110925/blog/plugins/A_ShareEntryWithSNS/script/shareEntryWithSNS.js", function(){
alert();
});
});
}
</script>
</body>
</html>
make javascript Speed Up (1)
Do you Think which sample is better between two samples
1. <html>
<head>
<script type ="text/javascript" src="file1.js"></script>
<script type ="text/javascript" src="file2.js"></script>
<script type ="text/javascript" src="file3.js"></script>
</head>
<body>
...
</body>
<html>
2. <html>
<head>
</head>
<body>
...
//end of body
<script type ="text/javascript" src="file1.js"></script>
<script type ="text/javascript" src="file2.js"></script>
<script type ="text/javascript" src="file3.js"></script>
</body>
<html>
First is well-known pattern when we use javascript, and also we learn like 1 sample
but until scripts are fully loaded we will see white page
Second sample is better than first
because after body is loaded javascript will run
1. <html>
<head>
<script type ="text/javascript" src="file1.js"></script>
<script type ="text/javascript" src="file2.js"></script>
<script type ="text/javascript" src="file3.js"></script>
</head>
<body>
...
</body>
<html>
2. <html>
<head>
</head>
<body>
...
//end of body
<script type ="text/javascript" src="file1.js"></script>
<script type ="text/javascript" src="file2.js"></script>
<script type ="text/javascript" src="file3.js"></script>
</body>
<html>
First is well-known pattern when we use javascript, and also we learn like 1 sample
but until scripts are fully loaded we will see white page
Second sample is better than first
because after body is loaded javascript will run
Monday, November 4, 2013
make Callback function and check if it is undefine in javascript
<!DOCTYPE html>
<html>
<script>
window.onload = hello;
function hello(){
test(function aaa(){
alert('callback success');
});
test();
}
function test(callback){
if(typeof callback != 'undefined'){
callback();
}
}
</script>
</html>
<html>
<script>
window.onload = hello;
function hello(){
test(function aaa(){
alert('callback success');
});
test();
}
function test(callback){
if(typeof callback != 'undefined'){
callback();
}
}
</script>
</html>
Sunday, November 3, 2013
basic javascript 3type alert
JavaScript supports three important types of dialog boxes. These dialog boxes
can be used to raise and alert, or to get confirmation on any input or to have a
kind of input from the users.
Here we will see each dialog box one by one:
An alert dialog box is mostly used to give a warning message to the users. Like if one input field requires to enter some text but user does not enter that field then as a part of validation you can use alert box to give warning message as follows:
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button "OK" to select and proceed.
A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two buttons: OK and Cancel.
If the user clicks on OK button the window method confirm() will return true. If the user clicks on the Cancel button confirm() returns false. You can use confirmation dialog box as follows:
The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus it enable you to interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two parameters (i) A label which you want to display in the text box (ii) A default string to display in the text box.
This dialog box with two buttons: OK and Cancel. If the user clicks on OK button the window method prompt() will return entered value from the text box. If the user clicks on the Cancel button the window method prompt() returns null.
You can use prompt dialog box as follows:
Here we will see each dialog box one by one:
Alert Dialog Box:
An alert dialog box is mostly used to give a warning message to the users. Like if one input field requires to enter some text but user does not enter that field then as a part of validation you can use alert box to give warning message as follows:
<head> <script type="text/javascript"> <!-- alert("Warning Message"); //--> </script> </head> |
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button "OK" to select and proceed.
Confirmation Dialog Box:
A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog box with two buttons: OK and Cancel.
If the user clicks on OK button the window method confirm() will return true. If the user clicks on the Cancel button confirm() returns false. You can use confirmation dialog box as follows:
<head> <script type="text/javascript"> <!-- var retVal = confirm("Do you want to continue ?"); if( retVal == true ){ alert("User wants to continue!"); return true; }else{ alert("User does not want to continue!"); return false; } //--> </script> </head> |
Prompt Dialog Box:
The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus it enable you to interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two parameters (i) A label which you want to display in the text box (ii) A default string to display in the text box.
This dialog box with two buttons: OK and Cancel. If the user clicks on OK button the window method prompt() will return entered value from the text box. If the user clicks on the Cancel button the window method prompt() returns null.
You can use prompt dialog box as follows:
<head> <script type="text/javascript"> <!-- var retVal = prompt("Enter your name : ", "your name here"); alert("You have entered : " + retVal ); //--> </script> </head> |
Wednesday, October 23, 2013
Let me make replaceAll in Javascript
There is no replaceAll in javascript
if you use replace
ex) var orgStr = "welcome to my blog to have a fun";
orgStr = orgStr.replace('to', 'ha');
console.log(orgStr);
output = "welcome ha my blog to have a fun"
It mean only first String will be replaced but otheres not,
So this is good solution
var orgStr = "welcome to my blog to have a fun";
orgStr = orgStr.split('to').join('ha');
console.log(orgStr);
output = "welcome ha my blog ha have a fun"
if you use replace
ex) var orgStr = "welcome to my blog to have a fun";
orgStr = orgStr.replace('to', 'ha');
console.log(orgStr);
output = "welcome ha my blog to have a fun"
It mean only first String will be replaced but otheres not,
So this is good solution
var orgStr = "welcome to my blog to have a fun";
orgStr = orgStr.split('to').join('ha');
console.log(orgStr);
output = "welcome ha my blog ha have a fun"
Subscribe to:
Posts (Atom)