블로그 이미지
윤영식
Full Stacker, Application Architecter, KnowHow Dispenser and Bike Rider

Publication

Category

Recent Post

2013. 11. 28. 09:32 HTML5, CSS3/CSS

Bootstrap은 CSS Framework으로 프리젠테이션을 담당하고 jQuery UI 와 Angular.js는 자체 컨트롤도 가지고 있지만 DOM 핸들링을 한다. 만일 서비스를 만드는데 Bootstrap + jQuery UI 조합일 때 또는 Bootstrap + Angular.js 조합일 때 그리고 Bootstrap + jQuery UI + Angular.js 조합 일때 프리젠테이션을 통합하는 방법은 어떤 것들이 있을까? 각 조합에 대해 어떻게 사용할지 알아보자.



1. Twitter Bootstrap 만 사용할 경우 

  - 부트스트랩만 놓고 보면 CSS Framework으로써 기본적인 Fluid Layout 형태와 기본 HTML 컨트롤의 모양을 정의하고 있다

    또한 JavaScript 기반 다양한 component들도 포함한다 

  - 부트스트랩의 CSS 부분을 향상시키고 extra component를 추가한 부분 변경모델은 Bootflat, Bootplus, FlatStrap, LeapStrap

  - 또는 다양한 완성체 템플릿을 startBootstrap같은 곳에서 만들어 제공도 한다 

    



2. Twitter Bootstrap + jQuery UI  함께 사용할 경우 (이제 없어졌다)

  - 문제는 여기서 부터 시작한다 

  - Bootstrap의 CSS 스타일이 존재하고 jQuery UI 도 자체 theme을 CSS로 정의하고 있다

  - Boottrap의 CSS를 jQuery UI에 접목하여 사용할 경우는 jQuery UI Widgets 에 대해서 Bootstrap theme을 입힌 것을 사용한다

    http://addyosmani.github.io/jquery-ui-bootstrap/

    



3. Twitter Bootstrap + Angular.js 함께 사용할 경우

  - Angular에 JavaScript component를 포팅하기 위하여 Directive로 감싸야하는 문제가 있다

  - jQuery UI와 Bootstrap theme을 결합하였다면 Angular.js 와 Bootstrap theme 을 결합하고 있다

  - 하지만 이것은 Bootstrap v2.3.* 버전의 component를 Angular.js Directive로 구현하는 것이다

    http://angular-ui.github.io/bootstrap/

    



4. Twitter Bootstrap + jQuery UI + Angular.js 함께 사용할 경우 

  - 해당 형태는 3번의 연장선으로 보면 된다 

  - Twitter Bootstrap의 javascript component를 Angular.js Directive화 하였듯, jQuery UI component들도 Directive화 한것이다 

    http://angular-ui.github.io/

     

   - 소스 : https://github.com/angular-ui/


기존의 JavaScript Component를 처리하려면 Directive화 과정을 거쳐야 하는데 이런 번거로운 과정을 해소하고자 Bootstrap의 JavaScript Component를 Directive로 만들어 놓은 Angular UI Bootstrap이 나왔다. jQuery UI를 지원하기 위하여 Angular UI 에 상당부분 즐겨 사용하는 JavaScript Component를 포함시켰으나 이 또한 jQuery UI의 모든 것을 커버하고 있지는 못하다. 


이래저래 문제되는 것은 Angular.js를 기반으로 개발할 때 UI를 담당하는 JavaScript Component를 Angular.js의 Directive화를 잘 해야 한다는 것이다. 



<참조>

  - Bootstrap ToolBox : 다양한 UI 컴포넌트들 

posted by 윤영식
2013. 11. 28. 07:08 My Projects/BI Dashboard

BI Dashboard 인 만큼 엑셀의 그리드 형태의 표현은 필수적이다. 오픈소스중에서 가장 많이 사용하고 있는 jqGrid를 Angular.js에 포팅하고 RESTful API를 호출하여 표현하는 방법을 알아보자.  




1. jqGrid 설치하기 

  - 최신버전 v4.5.4

  - jqGrid만을 MIT 라이센스하에서 사용을 할 수 있다. 

// bower 통하여 설치하기

$ bower install jqgrid --save


// index.html 에 설정하기

<!-- build:css(.tmp) styles/main.css -->

    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">

    <link rel="stylesheet" href="bower_components/jqgrid/css/ui.jqgrid.css">

    <link rel="stylesheet" href="styles/main.css">

<!-- endbuild -->

... 중략 ...

<!-- build:js scripts/plugins.js -->

    <script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>

    <script src="bower_components/respond/respond.src.js"></script>

    <script src="bower_components/jqgrid/js/i18n/grid.locale-en.js"></script>

    <script src="bower_components/jqgrid/js/jquery.jqGrid.js"></script>

<!-- endbuild -->

  - jqgrid의 theme을 위하여 jquery-ui 의 theme을 입힌다 

// bowe 통하여 설치하기 

$ bower install jquery-ui --save


지금까지의 bower components 목록 버전 의존성

$ bower list

BIDashboard

├── angular#1.2.1 (1.2.2 available)

.. 중략 ..

│ └── angular#1.2.1

├─┬ bootstrap#3.0.2

│ └── jquery#1.9.1 (2.0.3 available)

├── console-shim#05b957a4b1

├── es5-shim#2.0.12 (latest is 2.1.0)

├── jqgrid#4.5.4

├── jquery#1.9.1 (latest is 2.0.3)

├── jquery-migrate#1.2.1

├─┬ jquery-ui#1.10.3

│ └── jquery#1.9.1 (2.0.3 available)

├── json3#3.2.5 (3.2.6 available)

├── modernizr#2.7.0

└── respond#1.3.0


// index.html 에 설정하기 

<!-- build:css(.tmp) styles/main.css -->

    <link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">

    <link rel="stylesheet" href="bower_components/jquery-ui/themes/smoothness/jquery-ui.css">

    <link rel="stylesheet" href="bower_components/jqgrid/css/ui.jqgrid.css">

    <link rel="stylesheet" href="styles/main.css">

<!-- endbuild -->

... 중략 ...

<!-- build:js scripts/plugins.js -->

    <script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>

    <script src="bower_components/respond/respond.src.js"></script>

    <script src="bower_components/jquery-ui/ui/jquery-ui.js"></script>

    <script src="bower_components/jqgrid/js/i18n/grid.locale-en.js"></script>

    <script src="bower_components/jqgrid/js/jquery.jqGrid.js"></script>

<!-- endbuild -->



2. jqGrid 테스트 메뉴 추가하기 

  - 기존 프로그램에서 jqGrid 테스트 메뉴를 추가한다 

    + step-1 : views 폴더 밑으로 jqGridTest.html 파일 생성

    + step-2 : scripts 폴더 밑으로 biz 폴더 만들고 (여기선 sales) jqGridBiz.js 파일 생성 (화면 : 비즈니스모듈 = 1:1)

                   jqGridBiz.js 의 모듈 명칭, 컨트롤러 명칭을 정의한다 

    + step-3 : Main Application (DashboardApp.js) 안에 신규 Biz 모듈 설정 및 Routing 환경 설정

    + step-4 : index.html 안에 jqGridBiz.js 스크립트 태그 추가

    + step-5 : index.html 안의 메뉴설정에 jqGridTest.html이 보일 수 있도록 routing url 설정

// step-1

// views/jqGrid.html 파일 내역

jqGrid Test Page


// step-2

'use strict';

var RestTestBiz = angular.module('DasbhoardApp.JqGridBiz', ['DasbhoardApp.RestfulSvc']);

RestTestBiz.controller('JqGridBiz.salesCtrl', ['$scope', 'RestfulSvcApi', function ($scope, RestfulSvcApi) {


}]);


// step-3

// DashboardApp.js 변경 내역 

'use strict';

var DashboardApp = angular.module('DasbhoardApp', [

  'ngRoute',                                                  

  'ngCookies',

  'ngResource',

  'ngSanitize',

  'DasbhoardApp.CommonCtrl',

  'DasbhoardApp.RestTestBiz',

  'DasbhoardApp.JqGridBiz',

  'DasbhoardApp.RestfulSvc'

]);


DashboardApp.config(['$routeProvider', function ($routeProvider) {

    $routeProvider

      .when('/', {

        templateUrl: 'views/main.html'

      })

      .when('/resttest', {

        templateUrl: 'views/restTest.html',

        controller: 'RestTestBiz.personCtrl'

      })

      .when('/jqgridtest', {

        templateUrl: 'views/jqGridTest.html',

        controller: 'JqGridBiz.salesCtrl'

      })

      .otherwise({

        redirectTo: '/'

      });

  }]);


// step-4

// index.html 에 추가 

<!-- build:js scripts/dashboard-spa.js -->

    <script src="scripts/DashboardApp.js"></script>

    <script src="scripts/common/controllers/CommonCtrl.js"></script>

    <script src="scripts/common/services/RestfulSvc.js"></script>

    <script src="scripts/person/RestTestBiz.js"></script>

    <script src="scripts/sales/JqGridBiz.js"></script>

<!-- endbuild -->


// step-5

// index.html 의 메뉴 부분에 추가 

<ul class="nav navbar-nav">

<li data-ng-class="activeWhen(path()=='/')">

 <a href="" data-ng-click="setRoute('/')">Home</a>

</li>

<li data-ng-class="activeWhen(path()=='/resttest')">

 <a href="" data-ng-click="setRoute('/resttest')">RESTTest</a>

</li>

<li data-ng-class="activeWhen(path()=='/jqgridtest')">

 <a href="" data-ng-click="setRoute('/jqgridtest')">jqGridTest</a>

</li>

</ul>


// final

// 디렉토리 구조

// http://localhost:8080/#/jqgridtest  호출 결과 



3. jqGrid 의 Angular.js 적용전략 - Directive 만들기 

  - jqGridTest.html partial view html 안에 일반적인 jqGrid 표현 내역을 입력하면 화면에 아무것도 출력되지 않는다

    즉, jqGrid 사용하기 와 같은 <table> 태그와 <script> 태그를 jqGridTest.html 넣으면 화면출력이 되지 않는다는 것이다. 

    이는 Angular.js router를 통하여 partial html이 보여질 때 DOMP (DOM Parser)는 html만을 파싱하여 add 할 뿐이고, 

    <script> 태그는 수행되지 않기 때문이다 (참조)

  - jqGrid에 대한  Common Directive 만들기 : JqGridDrtv.js 

// Directive 모듈 JqGridDrtv.js 개발

'use strict';

var jqGridDrtv = angular.module('DashboardApp.JqGridDrtv', [ 'DasbhoardApp.RestfulSvc' ]);


/**

 * mc is Mobile Convergence of MobiConSoft

 * @use : <mc-jq-grid config="config" data="data"></mc-jq-grid>

 * config and data is used in Controller of Angular.js

 */

jqGridDrtv.directive('mcJqGrid', [ 'RestfulSvcApi', function(RestfulSvcApi) {

return {

restrict : 'E',

scope : {

config : '=',

data : '=',

},

link : function(scope, element, attrs) {

var table;

                         // config attribute 값의 변경을 체크하여 반영한다 

scope.$watch('config', function(newValue) {

element.children().empty();

table = angular.element('<table></table>');

element.append(table);

$(table).jqGrid(newValue);

});

                        // data attribute 값의 변경을 체크하여 반영한다 

scope.$watch('data', function(newValue, oldValue) {

var i;

for (i = oldValue.length - 1; i >= 0; i--) {

$(table).jqGrid('delRowData', i);

}

for (i = 0; i < newValue.length; i++) {

$(table).jqGrid('addRowData', i, newValue[i]);

}

});

}

};

} ]);

  - 메뉴에서 동작하도록 적용하기 

    + step-1 : Controller에 JqGridDrtv.js의 config, data attribute에 대한 샘플 데이터 설정을 한다 

    + step-2 : DashboardApp 안에 JqGridDrtv 모듈 의존관계를 설정한다

    + step-3 : index.html 안에 JqGridDrtv.js <script> 태그에 포함시킨다 

    + step-4 : jqGridTest.html 에 <mc-jq-grid> 태그를 포함시킨다 

// step-1 : JqGridBiz.js 에서 config, data 값 설정

'use strict';

var JqGridBiz = angular.module('DasbhoardApp.JqGridBiz', ['DasbhoardApp.RestfulSvc']);


JqGridBiz.controller('JqGridBiz.salesCtrl', ['$scope', 'RestfulSvcApi', function ($scope, RestfulSvcApi) {

$scope.config = {

  datatype: "local",

  height: 150,

    colNames:['Inv No','Date', 'Client', 'Amount','Tax','Total','Notes'],

    colModel:[

    {name:'id',index:'id', width:60, sorttype:"int"},

    {name:'invdate',index:'invdate', width:90, sorttype:"date"},

    {name:'name',index:'name', width:100},

    {name:'amount',index:'amount', width:80, align:"right",sorttype:"float"},

    {name:'tax',index:'tax', width:80, align:"right",sorttype:"float"},

    {name:'total',index:'total', width:80,align:"right",sorttype:"float"},

    {name:'note',index:'note', width:150, sortable:false}

    ],

    multiselect: true,

    caption: "Manipulating Array Data"

   };

   

$scope.data = [

{id:"1",invdate:"2007-10-01",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"},

{id:"2",invdate:"2007-10-02",name:"test2",note:"note2",amount:"300.00",tax:"20.00",total:"320.00"},

{id:"3",invdate:"2007-09-01",name:"test3",note:"note3",amount:"400.00",tax:"30.00",total:"430.00"},

{id:"4",invdate:"2007-10-04",name:"test",note:"note",amount:"200.00",tax:"10.00",total:"210.00"},

];

}]);


// step-2 : DashboardApp.js에서 의존성 설정

var DashboardApp = angular.module('DasbhoardApp', [

  'ngRoute',                                                  

  'ngCookies',

  'ngResource',

  'ngSanitize',

  'DasbhoardApp.CommonCtrl',

  'DashboardApp.JqGridDrtv',

  'DasbhoardApp.RestTestBiz',

  'DasbhoardApp.JqGridBiz',

  'DasbhoardApp.RestfulSvc'

]);


// step-3 : index.html 에서 <script> 태그 추가 

<!-- build:js scripts/dashboard-4.js -->

    <script src="scripts/DashboardApp.js"></script>

    <script src="scripts/common/controllers/CommonCtrl.js"></script>

    <script src="scripts/common/directives/JqGridDrtv.js"></script>

    <script src="scripts/common/services/RestfulSvc.js"></script>

    <script src="scripts/person/RestTestBiz.js"></script>

    <script src="scripts/sales/JqGridBiz.js"></script>

<!-- endbuild -->


// step-4 : jqGridTest.html 안에 <mc-jq-grid> 태그를 넣는다 

<div id="gridtest" class="container">

<div class="row">

<div class="col-md-8 alert alert-info">

<i class="icon-hand-right"></i> This is jqGrid Directive for AngularJS

</div>

</div>

<mc-jq-grid config="config" data="data"></mc-jq-grid>

</div>


// 최종결과 

// 디렉토리 구조



4. jqGrid에 Bootstrp CSS 적용하기 

  - jqGrid는 기본적으로 jquery-ui theme을 사용한다. Bootstrap으로 기본적인 Layout과 controller를 사용하면 Grid 또한 같은 사용자 경험을 주어야  한다 

  - jqGrid에 Bootstrap과 유사한 CSS 값이 적용된 화면 참조 (소스)

  - 적용 순서

    + styles/main.css 안에 jgGrid.bootstrap.css 내역을 복사하여 넣는다

    + main.css 가 맨밑에 있으므로 jqgrid의 css를 다시 쓰는 역할이다 

<!-- build:css(.tmp) styles/main.css -->

<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">

<link rel="stylesheet" href="bower_components/jquery-ui/themes/smoothness/jquery-ui.css">

<link rel="stylesheet" href="bower_components/jqgrid/css/ui.jqgrid.css">

<link rel="stylesheet" href="styles/main.css">

<!-- endbuild -->

  - 결과 

    



* jQuery UI를 Angular.js에 적용하는 방법

  - Bootstrap 스타일의 CSS를 적용했다면 그다음은 Directive로 만든 jqGrid의 column sorting을 시도해 보자 

  - column우측을 클릭하면 contents 영역에서 "loading..." 메세지만 나오고 sorting이 되지않을 것이다. 해결해 보자 

   


  - jQuery Plugins을 Directive로 만드는 이유 (참조)

// 하기와 같은 코드가 있을 경우 controller scope에서 동작을 하지 않으며, model의 변경도 반영되지 않는다

$('.datepicker').datepicker();


// 안될 경우 Angular.js 의 Directive 생성하여 동작토록 만들어야 한다

// datepicker를 wrapping한 directive 소스 

var directives = angular.module('directives', []);

directives.directive('datepicker', function() {

   return function(scope, element, attrs) {

       element.datepicker({

           inline: true,

           dateFormat: 'dd.mm.yy',

           onSelect: function(dateText) {

               // input field의 jQuery Object

               var modelPath = $(this).attr('ng-model');

               // angular.js $parse와 동일한 역할

               // modelPath = a.b.c , scope = {}, dateText = 2013.11.27 이면 리턴값은 {a : { b : { c: '2013.11.27 }}} 됨

               putObject(modelPath, scope, dateText);  

               scope.$apply();

           }

       });

   }

});


// html 태그에서 datepicker attribute 로 사용한다 

<input type="text" datepicker ng-model="myobj.myvalue" />

  - Directive를 만들어주는 function의 파라미터 값의 의미

    + scope : controller가 관장하는 scope

    + element : jQuery object

    + attrs : 태그의 attribute 속성 key/value

  - datepicker의 callback function을 정의

    + onSelect : 사용자가 date을 선택했을 때 수행할 datepicker의 callback 이다 

    + $apply : 해당 controller scope에 변경값을 적용하기 위하여 scope.$apply를 호출해야 한다 (참조)

  - 데이터가 Object.properties 형태로 관리될 때 좀 더 우아하게 처리하는 방법은 $parse를 이용한다 (참조)

    + step-1 : 선택한 값은 controller의 scope안에 반영시키기 위하여 attrs.ngModel로 가져와서 $parse 파싱한다 

    + step-2 : 날짜의 값을 선택하여 해당 scope의 ngModel에 assign 반영한다 

myApp.directive('datepicker', function ($parse) {

    return function (scope, element, attrs, controller) {

        // step-1

        var ngModel = $parse(attrs.ngModel);

        $(function(){

            element.datepicker({

               ...

               onSelect:function (dateText, inst) {

                    scope.$apply(function(scope){

                        // step-2 Change binded variable

                        ngModel.assign(scope, dateText);

                    });

               }

            });

        });

    }

});

 

function MyCtrl($scope) {

    $scope.userInfo = {

        person: {

            mDate: '1967-10-07'

        }

    };  

 

 * 다른 jQuery UI 들의 Directive 소스

 * 소스 : https://github.com/ysyun/SPA_Angular_SpringFramework_Eclipse_ENV/tree/feature_jqgrid_angular

 


새로운 Directive IE8 에 적용하기

  - IE8에서는 새로운 directive를 만들어 element 태그로 사용할 경우 

  - IE8 이하일 경우 DOM을 만들어준다 (참조, 호환성가이드)

 <head>

    <!--[if lte IE 8]>

      <script>

        document.createElement('mc-jq-grid');

      </script>

    <![endif]-->

</head>



<참조>

  - Partial View html에서 javascript코드가 적용안되는 이유

  - jqGrid Directives 만들기

  - jqGrid에 Bootstrap CSS 적용하기

  - jQuery UI를 datepicker를 Angular.js Directive로 적용하기

  - jQuery UI를 Angular.js Directive로 만든 소스(GitHub) 

  - $parse를 이용하여 a.b.c 으로 시작하는 것을 json object 형태로 바꾸어주는 방법

posted by 윤영식
2013. 11. 12. 01:45 HTML5, CSS3/jQuery

jQueryUI는 jQuery를 기본으로 하면서 뷰를 표현하는 다양한 컴포넌트, 위젯을 모아놓은 User Interface를 모아 놓은 것이다. 어떻게 시작할 수 있는지 알아보자 




1. 사전 지식

  - 먼저 데모페이지에서 어떤 종류의 컴포넌트가 있는지 보자 

  - 여러 종류의 컴포넌트중 사용하길 원하는 부분만 Download Builder 를 통하여 다운로드한다



2. 파일 다운로드하기 

  - Download Builder에서 필요한 컴포넌트 -Core, Interactions, Widgets, Effects - 를 선택한다. 

  - 사용할 테마(Theme)를 선택한다. ThemeRoller 에서 사용자 정의도 가능하고 이미 만들어진 것을 선택할 수 있다

  - jQuery UI 버전 - 1.10.3/1.9.2 - 을 선택한다. jQuery 버전은 1.6 이상을 요구한다

  - 마지막으로 download 버튼을 클릭한다. 다운로드 파일 예) jquery-ui-1.10.3.custom.zip

// 압추을 풀면 폴더와 파일 존재한다. index.html 를 브라우져에서 확인해 볼 수 있다

/css

/development-bundle

/ js

index.html 

  - index.html 의 내용

// css를 추가

<link rel="stylesheet" href="css/themename/jquery-ui.custom.css" />

// jquery를 먼저 위치시킴

<script src="js/jquery.min.js"></script>

// jquery-ui를 위치시킴

<script src="js/jquery-ui.custom.min.js"></script>

  - smoothness theme을 선택했을 경우




3. 사용자 정의하기

  - JSON 형태로 옵션 객체를 전달한다. API를 확인하고 설정한다

$( "#mySliderDiv" ).slider({

    orientation: "vertical",

    min: 0,

    max: 150,

    value: 50

});

  - jQuery UI 개발에 참여하고 싶다면 Development Center로...



4. 동작방식 이해하기 

  - jQuery UI widgets은 공통 API를 제공하는 Widget Factory 기반으로 생성된다

  - Widget Life Cycle

    + Initialization : 플로그인을 펑션을 호출한다. 옵션이 없으면 default 옵션이 적용된다 

$( "#elem" ).progressbar();

또는

$( "#elem" ).progressbar({ value: 20 });

    + Methods : 최기화 된 후 상태를 조회하거나 액션을 수행할 수 있다. 메소드 이름 "value" 호출하여 40을 설정. 체이닝 호출 가능함.

$( "#elem" )

    .progressbar( "value", 90 )

    .addClass( "almost-done" );

    + Command Methods : option, disable, enable, destroy, widget 

$( "#elem" ).progressbar( "disable" );

$( "#elem" ).progressbar( "enable" );

$( "#elem" ).progressbar( "distroy" );

    + Events : 모든 동작에 대한 위젯별 이벤트 콜백 펑션을 설정한다. 공통 이벤트는 위젯 생성후 호출되는 create 이 존재함

// bind 호출 후 위젯명+이벤트명 연결하여 호출 

$( "#elem" ).bind( "progressbarchange", function() {

    alert( "The value has changed!" );

});


// 위젯 호출 후 change에 콜백 펑션 정의

$( "#elem" ).progressbar({

    change: function() {

        alert( "The value has changed!" );

    }

});

 


5. 테마 설정하기 

  - 기본적으로 jQuery UI CSS Framework - ui.theme.css - 와 plugin 별 CSS가 조합되어 만들어진다

    + ui.theme.css는 ThemeRoller 를 통하여 변경하는 경우

    + ui.theme.css 또는 widget plugin css를 직접 CSS를 변경하는 경우

    + 완전히 새로운 CSS를 만드는 경우 예) Twitter Bootstrap CSS를 jQuery UI에 적용 

    



6. CSS Framework API 이해 

  - ui.core.css 와 ui.theme.css 두개로 분리된다  

  - Layout Helpers : .ui-helper-*

  - Widget Containers : .ui-widget-*

  - Interaction States/Cues : .ui-state-*

  - Icon : .ui-icon 형식) .ui-icon-{icon type}-{icon sub description}-{direction}

  - Corner Radius : .ui-corner-*

  * jQuery UI Theme Base 깃헙 소스



7. 직접 Theme 만들기 

  - 디렉토리 구조 만들기 

// 1. themename 폴더 만들기 

/themename


// 2. 기본 css 파일 만들기

/themename/themename.css


// 3. 플러그인 css 파일 만들기 

/themename/themename.pluginname.css


// 4. 이미지 포함하기 

/themename/img.png

  - 스타일링 : .ui-themename 으로 한다면 하기와 같이 사용한다 

<html>

<head>

    <title>My Site</title>

    <link rel="stylesheet" href="themename/themename.css" />

    <link rel="stylesheet" href="othertheme/othertheme.css" />

    <link rel="stylesheet" href="othertheme/othertheme.dialog.css" />

</head>

<body class="ui-themename">

    <div class="ui-othertheme">

        <div class="ui-dialog">This is a modal dialog.</div>

    </div>

</body>

</html>



8. Widget Factory 사용하기 

  - 위젯 만드는 일관성을 보장하기 위함 

  - jQuery.widget 또는 $.widget 호출을 통하여 만든다

    + Context Object 이다. DOM은 아니다

    + Single Object로 생성된다 

// 1) namespace 는 한개의 depth만 허용하여 만들 수 있다. 여기서는 custom 이 namespace 이다 

$.widget( "custom.progressbar", {

 

   // 2) instance의 option내역 및 default 값 정의 

    options: {

        value: 0

    },

 

   // 3) 위젯 생성

    _create: function() {

        var progress = this.options.value + "%";

        // jQuery Object 

        this.element

            .addClass( "progressbar" )

            .text( progress );

    },

 

    // 4) 사용할 메소드 생성

    // Create a public method.

    value: function( value ) {

 

        // No value passed, act as a getter.

        if ( value === undefined ) {

            return this.options.value;

        }

 

        // Value passed, act as a setter.

        this.options.value = this._constrain( value );

        var progress = this.options.value + "%";

        this.element.text( progress );

    },

 

    // Create a private method. _ 즉 underscore를 하면 private 메소드가 된다 

    _constrain: function( value ) {

        if ( value > 100 ) {

            value = 100;

        }

        if ( value < 0 ) {

            value = 0;

        }

        return value;

    }

});

  - 사용하기 

var bar = $( "<div></div>" )

    .appendTo( "body" )

    .progressbar({ value: 20 });

 

// Get the current value.

alert( bar.progressbar( "value" ) );

 

// Update the value.

bar.progressbar( "value", 50 );

 

// Get the current value again.

alert( bar.progressbar( "value" ) );

  - 그외 Option 동작, Triggering CallBack Function, CleanUp with Destroy방법은 링크 참조한다



<참조>

  - jQuery UI Getting Start 

  - jQuery UI How to Work 

  - Theming jQuery UI

  - jQuery UI CSS Framework API

  - jQuery UI Theme Base 깃헙 소스

  - Twitter Bootstrap CSS를 jQuery UI에 적용

  - How to Use Widget Factory

posted by 윤영식
prev 1 next