TIP게시판

제목 sortable javascript and php, mysql
글쓴이 건곤대나이 작성시각 2015/10/14 22:20:29
댓글 : 1 추천 : 0 스크랩 : 0 조회수 : 16541   RSS
최근 개발과제를 수행하면서 의외로 기본적인 주제들을 간과한 경우가 많다는 것을 느꼈습니다.

그중에 하나가 html element의 정렬에 대한 부분입니다.

구글링으로 여러가지 솔루션을 찾았지만 그중 제가 선택한것은

http://rubaxa.github.io/Sortable/ 입니다.

특징은 모바일에서도 적용이되며 최우선적으로 기존에 제가 만든 것과 충돌이 일어나지 않아서 선택한 것입니다.
또한 dynamic하게 생성된 element도 처리를 해주니 딱이더군요.

XE용으로 제작했지만 CI에서도 충분히 적용 가능하리라 봅니다.
코드 최적화는 안되어 있습니다 ㅡ.ㅡ ;

아래 코드는 파일 업로딩후 파일 순서를 재정렬하는 것입니다.

***

자바스크립트 부분

    $(document).ready(function() {
        //
        
        file_upload('write', 'document_srl', '{$document_srl}', 'photo');
        file_upload('write', 'document_srl', '{$document_srl}', 'vrpano');
        
        var sortable = [];
        [].forEach.call(document.getElementsByClassName( 'AXUpload5QueueBox' ), function (el){
            var form = $( el ).closest( 'form' );
            var target_mode = $( el ).closest( '.tab-pane' ).attr( 'data-mode' );
            
            //var sortable = Sortable.create(el);
            sortable[ target_mode ] = new Sortable(el, {
                //group: "name",  // or { name: "...", pull: [true, false, clone], put: [true, false, array] }
                sort: true,  // sorting inside list
                delay: 0, // time in milliseconds to define when the sorting should start
                disabled: false, // Disables the sortable if set to true.
                store: null,  // @see Store
                animation: 150,  // ms, animation speed moving items when sorting, `0` — without animation
                //handle: ".my-handle",  // Drag handle selector within list items
                //filter: ".ignore-elements",  // Selectors that do not lead to dragging (String or Function)
                //draggable: ".item",  // Specifies which items inside the element should be sortable
                ghostClass: "sortable-ghost",  // Class name for the drop placeholder
                chosenClass: "sortable-chosen",  // Class name for the chosen item
                dataIdAttr: 'data-id',

                forceFallback: false,  // ignore the HTML5 DnD behaviour and force the fallback to kick in
                fallbackClass: "sortable-fallback",  // Class name for the cloned DOM Element when using forceFallback
                fallbackOnBody: false,  // Appends the cloned DOM Element into the Document's Body

                scroll: true, // or HTMLElement
                scrollSensitivity: 30, // px, how near the mouse must be to an edge to start scrolling.
                scrollSpeed: 10, // px

                setData: function (dataTransfer, dragEl) {
                    dataTransfer.setData('Text', dragEl.textContent);
                },

                // dragging started
                onStart: function (/**Event*/evt) {
                    evt.oldIndex;  // element index within parent
                },

                // dragging ended
                onEnd: function (/**Event*/evt) {
                    evt.oldIndex;  // element's old index within parent
                    evt.newIndex;  // element's new index within parent
                },

                // Element is dropped into the list from another list
                onAdd: function (/**Event*/evt) {
                    var itemEl = evt.item;  // dragged HTMLElement
                    evt.from;  // previous list
                    // + indexes from onEnd
                },

                // Changed sorting within list
                onUpdate: function (/**Event*/evt) {
//console.log(evt);
                    //var itemEl = evt.item;  // dragged HTMLElement
                    // + indexes from onEnd
                    
                    var form = $( evt.item ).closest( 'form' );
                    var target_mode = $( evt.item ).closest( '.tab-pane' ).attr( 'data-mode' );
                    var params={}, responses=['error','message','document_srl'], file_srls=[], list_orders=[];
                    
                    $( form.find( '[data-mode='+target_mode+'] .AXUpload5QueueBox > li' ) ).each(function(index) {
                        var file_srl = $(this).attr( 'data-file_srl' );
                        var list_order = $(this).attr( 'data-list_order' );
                        
                        file_srls.push( file_srl );
                        list_orders.push( list_order );
                    });
                    params['upload_target_srl'] = form.find('input[name=document_srl]').val();
                    params['mid'] =               form.find('input[name=mid]').val();
                    params['target_mode'] =       target_mode;
                    params['file_srls'] =         file_srls;
                    params['list_orders'] =       list_orders;
//console.log(params);
                    
                    exec_xml('realty', 'setRealtyFileOrder', params, function(responses){
                        if( empty(responses.error) ) {
                        }
                        else {
                        }
                    }, responses);
                },

                // Called by any change to the list (add / update / remove)
                onSort: function (/**Event*/evt) {
                    // same properties as onUpdate
                },

                // Element is removed from the list into another list
                onRemove: function (/**Event*/evt) {
                    // same properties as onUpdate
                },

                // Attempt to drag a filtered element
                onFilter: function (/**Event*/evt) {
                    var itemEl = evt.item;  // HTMLElement receiving the `mousedown|tapstart` event.
                },

                // Event when you move an item in the list or between lists
                onMove: function (/**Event*/evt) {
                    // Example: http://jsbin.com/tuyafe/1/edit?js,output
                    evt.dragged; // dragged HTMLElement
                    evt.draggedRect; // TextRectangle {left, top, right и bottom}
                    evt.related; // HTMLElement on which have guided
                    evt.relatedRect; // TextRectangle
                    // return false; — for cancel
                }
            });
        });
    });


PHP & MySQL

    function setRealtyFileOrder()
    {
        $vars = Context::getRequestVars();
        
        rsort ( $vars->list_orders );

        $oDB = DB::getInstance();
        $oDB->begin();

        foreach( $vars->file_srls as $key => $file_srl)
        {
            $sql = sprintf("UPDATE `%srealty_files` AS `realty_files` SET `list_order`=%d WHERE `file_srl`=%d", $oDB->prefix, $vars->list_orders[$key], $file_srl);
//var_dump($sql);exit;
            $result = $oDB->_query($sql);
            if( $oDB->isError() )
            {
                $oDB->rollback();
                $oDB_output = $oDB->getError();
                $oDB_output->setMessage( sprintf('%s %s : %s, %s', $oDB_output->getMessage(), $sql, __FUNCTION__, __LINE__ ) );
                return $oDB_output;
                /*$oDB->rollback();
                $this->stop($oDB->getMessage);*/
                //return $oDB->getError();
            }
        }
        
        // commit
        $oDB->commit();
    }

***

 
 다음글 텔레그램 푸시 봇 (6)
 이전글 데스크탑 크롬 에서 스마트폰의 모바일웹 및 앱의 웹뷰 ... (4)

댓글

한대승(불의회상) / 2015/10/15 11:23:31 / 추천 0
좋은 정보 감사 합니다.
필요한 곳에 유용하게 사용 할게요.