DevEnjoy

One Step Closer

Javascript

Frontend 자동화 도구

2016년 5월 31일 by YongPwi Leave a Comment
  • Yeoman
    • scaffolding tool
      • 조력, 발판
      • 초기 단계에 적절한 도움을 통한 작업시간 단축
    • web appliication 개발 전에 필요한 디렉토리 구조 및 기본적인 파일 생성
    • 목적에 따라 다르게 구조를 잡아준다
      • bootstrap app => bootstrap generator
      • angular js => angular generator
    • install
      • npm(window, linux)
      • node.js, ruby 의존성 때문에 설치 필요
      • // compass를 설치합니다. sass 컴파일 시 필요합니다.

        $ gem install compass

        // Yeoman을 설치합니다.

        $ npm install -g yo

    • generator에 따라 bower.json 자동 생성
      • bower을 사용하여 의존 컴포넌트를 자동으로 받아 scaffoling 생성
      • 추가 컴포넌트 필요시 bower.json에 추가 후 다시 install
    • scaffolding에 맞는 기본 Guntfile.js 자동 생성
      • 추가 task, 변경 필요한 task 존재시 yeoman이 생성한 gruntfile.js에 추가 or 수정
  • Bower(http://bower.io)
    • component 의존성 관리
    • npm, brew 비슷
    • 라이브러리 파일을 형상관리 하지 않아도 됨
  • Grunt, Gulp
    • Grunt(http://gruntjs-kr.herokuapp.com)
      • 자바스크립트 프로젝트를 위한 task 기반의 CLI(command line interface build too)
        • task – static file(js, css, html) concat, miniflcation
        • node.js에서 할수 있는 모느것을 프로젝트에 적용 가능
      • 반복되는 작업을 Gruntflie.js를 작성하여 자동 빌드, 배포
      • node.js 기반, 필수, npm으로 global로 설치해야함
      • grunt는 script파일인 Gruntfile.js를 참고하여 수행
    • Gulp
      • 플러그인을 연결해서 사용
      • node 스럽다.
        • 작은 모듈이 많고 이를 조합해서 테스크를 만든다.
      • 코드로 테스크를 선언

 

참고
http://javarouka.github.io/pt/yeoman
http://mobicon.tistory.com/402
http://e-rooms.tistory.com/entry/프론트-엔드-웹-개발을-위한-빌드-시스템Grunt-Yeoman-Bower
https://blog.outsider.ne.kr/1181?category=20

Posted in: Javascript, Programing Tagged: bower, Frontend, grunt, gulp, yeoman

jQuery Ajax에서 json Array 직렬화

2014년 10월 23일 by YongPwi 7 Comments

jQuery Ajax에서 data를 json 방식으로 Array를 전달하려고,,,

꽤 많은 삽질을 했다,,,

역시 안쓰면 금방 까먹는것 같다,,,

별다른건 없는데 form에 있는 데이터가 아니어서 강제적으로 json형태로 만들어 주고서

ajax call 하기만 하면 되는데 왜 안될까,,,

json 은 한개의 key 값으로 배열형태로 넘겼다,,,

그런데 server 단에서 getParameterNames을 받질 못하는 상황이 발생하였다,,,

넘어온 파라미터와 값을 찍어보니 내가 의도한 파라미터 명으로 넘어가지 않았다,,,

난 ‘key’ 명으로 배열로 받을거라 생각 했는데,,,

실제 넘어온건 ‘key[]’ 명으로 넘어왔다,,,

내가 json 데이터를 잘못 만들었나 싶어서 수 많은 삽질을 했다,,,

삽질과 구글링을 해보다 jquery.ajax api를 다시 좀보니,,,

data에 값이 배열인 경우에는 동일한 키값을 같는 직렬화 세팅을 해주는 문구가 있었다,,,

젠쟝,,,

결국은 하위 코드 주석처리 해놓은 traditional: true 를 추가해주니 의도한대로 ‘key’ 명으로 배열로 받을수 있었다,,,

사실 jQuery.param도 보긴 했는데,,,

꼼꼼하게 안보고 안된다는 생각에 무한 삽질 시간이 좀 후회스럽다,,,

jquery 1.4부터인가 바뀐거 같은데,,,

내가 마지막으로 써본 버전이 몇이던가,,,

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
var params = [];
var listSize = 5;
   for (var nRow = 0; nRow < listSize; nRow++) {
      params.push(nRow);
   }
$.ajax({
     url: callUrl,
     type: 'POST',
     data: {'key':params},
     dataType: 'json',
     //traditional: true,
     success: function (r) {
         
         });
     },
     error: function (xhr, status, error) {
                alert(xhr.status);
                alert(error);
     }  
});

//server단 확인
Enumeration em = request.getParameterNames();
while(em.hasMoreElements()){
    String parameterName = (String)em.nextElement();
    String parameterValue = request.getParameter(parameterName);
    String[] parameterValues = request.getParameterValues(parameterName);
    if(parameterValues != null){
         for(int i=0; i< parameterValues.length; i++){
             System.out.println("array_" + parameterName + "=" + parameterValues[i]);
         }
    } else {
         System.out.println(parameterName + "=" + parameterValue;
    }
}
Posted in: Javascript, Programing Tagged: ajax, array, jquery, json, traditional

facebook sdk 회원정보 연동 예제

2014년 2월 5일 by YongPwi 18 Comments

일전에 facebook sdk 연동 작업할때 작성해둔 예제인데,,,

결국 제품 오픈은 올해로 미뤄져서 묻혀버린 코드가,,,

오늘 지인과 이야기 하다가 필요하단 이야기를 듣고 문뜩 생각나서 정리해둔다,,,

작년 꽤나 삽질했던 기억이 있는데,,,지금도 동작할지는 모르겠다,,,

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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script language="javascript">
        // 페이스북 SDK 초기화
        window.fbAsyncInit = function () {
            FB.init({
                appId: ''    // Website with Facebook Login 사이트 : 일단 test 용으로 용퓌 계정상에서 app 생성
                , status: true   // check login status
                , cookie: true   // enable cookies to allow the server to access the session
                , xfbml: true    // parse XFBML
                //,oauth: true
            });
        };

        // 페이스북 SDK(js) 로딩 (페이지 로딩 속도 향상을 위해 사용)
        (function (d) {
            var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
            if (d.getElementById(id)) {
                return;
            }
            js = d.createElement('script');
            js.id = id;
            js.async = true;
            //js.src = "//connect.facebook.net/en_US/all.js";
            js.src = "http://connect.facebook.net/ko_KR/all.js";
            ref.parentNode.insertBefore(js, ref);
        }(document));

        // 페이스북 계정으로 회원 가입
        function facebookRegist() {
            // 페이스북 로그인 상태 체크
            FB.getLoginStatus(function (response) {

                if (response.status == "connected") {
                    // 페이스북 로그인 YES! and 앱 허가 YES!
                    handleFacebookRegist(response);
                } else if (response.status == "not_authorized") {
                    // 페이스북 로그인 YES! but 앱 허가 NO!
                    FB.login(function (response) {
                                handleFacebookRegist(response);
                            },
                            {scope: 'publish_stream, email, user_birthday, user_likes, publish_actions, read_stream'});
                } else {    // 페이스북 로그아웃 상태.
                    FB.login(function (response) {
                                handleFacebookRegist(response);
                            },
                            {scope: 'publish_stream, email, user_birthday, user_likes, publish_actions, read_stream'});
                }
            });
        }

        // 회원가입 핸들러
        function handleFacebookRegist(response) {

            var accessToken = response.authResponse.accessToken;
            var userId, userName, fbId, userBirth;

            FB.api('/me', function (user) {
                userId = user.email;    // 페이스북 email
                userName = user.name;   // 페이스북 name
                fbId = user.id;         // 페이스북 id
                userBirth = user.birthday;  // 페이스북 생일 : mm/dd/yyyy
                alert(userId);
                alert(userName);
                alert(userBirth);
                $('input[name=fbAccessToken]').val(accessToken);
                return;
                $.ajax({
                    type: "post",
                    url: "ajax 로 호출할 url",
                    dataType: "jsonp",
                    jsonp: "callback",
                    data: {
                        userId: userId
                    },
                    beforeSend: function () {
                        $('#ajax_load_indicator').fadeIn('fast');
                    },
                    success: function (data) {
                        if (data.result == true) {
                            alert("이미 가입이 되어있습니다.");
                            return;
                        } else {
                            if (confirm("Facebook 계정으로 가입하시겠습니까?\n\rFacebook 계정으로 가입시 추가정보를 입력하셔야 합니다.")) {
                                //var $form = $("<form></form>");
                                //$form.attr("action","페이스북에서 받은 정보를 post로 넘길 url");
                                //$form.attr("method","post");
                                //$form.appendTo("body");
                                //$form.append("<input type="hidden" name="userName" value=""+ userName +"">");
                                //$form.append("<input type="hidden" name="userId" value=""+ userId +"">");
                                //$form.append("<input type="hidden" name="fbId" value=""+ fbId +"">");
                                //$form.append("<input type="hidden" name="userBirth" value=""+ userBirth +"">");    // mm/dd/yyyy 형식으로 받음.(짤라서 쓰던가 하믄 됨.)
                                //$form.submit();
                            }
                            return;
                        }
                    },
                    error: function (data, status, err) {
                        alert("서버와의 통신이 실패했습니다.");
                        alert(err)
                        return;
                    },
                    complete: function () {
                        $('#ajax_load_indicator').fadeOut();
                    }
                });
            });
        }

        function fbNesFeedPost(){
            //자동 포스팅 시키기
            FB.api('/me/feed','post',
                    {
                        //method: 'feed',  //feed 로 올림
                        //name: '테스트',  // 링크가 걸리는 이름
                        //link: '클릭하면 넘어갈 주소',  // 링크 주소
                        //picture: '사진 주소',  // 사진
                        //caption: 'caption',  //
                        //description: 'description',  // 컨텐츠
                        message: '연동테스트' // 텍스트박스 안의 글자
                    },
                    function(response){
                        if(!response || response.error){
                            FB.login(function(response) {  // 자동 글 등록 실패시 권한 부여하는 창을 띄움
                                        Log.info('FB.login callback', response);
                                        if (response.status === 'connected') {Log.info('User is logged in');}
                                        else {Log.info('User is logged out');}
                                    },
                                    {scope: 'read_stream,publish_stream'}
                            );
                            //alert("facebook 권한 허가를 누르신 후 \n다시 눌러주십시오.");
                        }else{
                            alert("글 등록 성공");  //자동 글 등록 성공시
                        }
                    });
        }


    </script>
</head>
<body>
<form name="fbForm" method="post">
    <input type="text" name="fbAccessToken" value="">
    <input type="button" value="Facebook 연동" onclick="facebookRegist();">
    <input type="button" value="Facebook newsfeed연동" onclick="fbNesFeedPost();">
    <input type="text" name="message">
</form>
</body>
</html>
Posted in: Javascript, Programing Tagged: facebook

jquery .attr() .prod() 차이

2014년 1월 23일 by YongPwi 6 Comments

현재 운영 중인 시스템이 오래되다 보니 jquery를 정책상 사용하고 있지 않다. (물론 군데군데 쓰인 곳은 있음)

운영 정책을 지키는 편이어서 사용 안 하고 있었는데 얼마 전 jquery 기반 editor를 사용한 page 작업 중 뇌가 다시 쫀쫀해 졌다.

기존에 내가 알고 있던 속성에 대한 핸들링은 거의 .attr()을 사용하였다.

jquery 둘러보던 중에 .attr() .prod() 가 1.6버전부터 구분되어서 사용되고 있다는걸 이제 보았다. (반성하자,,,)

1.6 이전까지는 속성(attribute)과 프로퍼티(property)를 같이 사용하였지만 이후부터는 명시적으로 구분해서 사용한다.

 

 Code  Description(return)
elem.checked  true (Boolean) Will change with checkbox state
$( elem ).prop( “checked” )  true (Boolean) Will change with checkbox state
elem.getAttribute( “checked” )  “checked” (String) Initial state of the checkbox; does not change
$( elem ).attr( “checked” ) (1.6)  “checked” (String) Initial state of the checkbox; does not change
$( elem ).attr( “checked” ) (1.6.1+)  “checked” (String) Will change with checkbox state
$( elem ).attr( “checked” ) (pre-1.6)  true (Boolean) Changed with checkbox state

 

1
2
3
4
5
6
7
8
9
10
11
<input type="checkbox" name="agreement" />
<a id="test" href="test2">주소</a>

<script type="text/javascript">
   alert($('[name=agreement]').prop('checked'));   // true or false
   alert($('[name=agreement]').attr('checked'));   // checked or undefined
   
   var link = $('#test');
   alert(link.attr('href'));   // test2
   alert(link.prop('href'));   // http://localhost(절대주소)/test2
</script>

상위 코드 처럼 두개의 결과값은 다르게 나타난다.

이 두개의 메소드는 취급하는 정보가 다르다.

.attr()는HTML의 속성(attribute)을 .prop()는 JavaScript의 프로파티(property)를 취급하는 메소드이다.

그냥 “되네~!” 하고 넘어갔던 내용인데,,, 오늘도 다시 한번 반성하자.

Posted in: Javascript, Programing Tagged: .attr(), .prod(), jquery

Calendar

3월 2023
일 월 화 수 목 금 토
« 4월    
 1234
567891011
12131415161718
19202122232425
262728293031  

Recent Posts

  • ubuntu bastion 설정
  • Spring Boot properties 암호화
  • Git Repository Bitbucket과 Issue Tracker Redmine 연동 설정
  • Spring Security 동일 session 제어
  • Spring @Mock, @Mockbean, @InjectMock

Recent Comments

  • pzotov (Ubuntu 14.04에서 Sonarqube 6.7.1 service 등록)
  • cours de theatre paris (AWS ELB와 Auto Scaling 연동, nginx)
  • bayern munich (IntelliJ EAP Font rendering)
  • camiseta del chelsea (OS X에서 APP 아이콘 변경)
  • cheap football shirts replica (jQuery Ajax에서 json Array 직렬화)

Copyright © [the-year] [site-link].

Powered by [wp-link] and [theme-link].