Подтвердить что ты не робот

Jquery Сортировка connectWith вызывает метод обновления дважды

В приведенном ниже коде функция обновления вызывается дважды, когда элемент перемещается из списка sortable1 в sortable2. Хотя мне нужно вызвать эту функцию только один раз:

$("#sortable1 tbody, #sortable2 tbody").sortable({
    connectWith: '.connectedSortable tbody',
    helper: fixHelper,
    handle : '.handle',
    update : function () {
        var order = $('#sortable1 tbody').sortable('serialize');
    }    
}).disableSelection();
4b9b3361

Ответ 2

Ответ Стефана был хорош, но в нем не упоминается еще один кусочек головоломки, так что вот оно - на случай, если кто-то (как и я) не получит его сразу. Это должно помочь вам справиться со всем этим в функции update() и не путаться с receive() (который срабатывает только при перемещении между контейнерами):

update: function(e,ui) {
    if (this === ui.item.parent()[0]) {
        if (ui.sender !== null) {
          // the movement was from one container to another - do something to process it
          // ui.sender will be the reference to original container
        } else {
          // the move was performed within the same container - do your "same container" stuff
        }
    }
}

Ответ 4

Попробуйте следующее:

update: function(e,ui) {
    if (!ui.sender) {
        //your code here
    }
}

Ответ 5

Я просто столкнулся с этим. Это ошибка в пользовательском интерфейсе jQuery, см. http://bugs.jqueryui.com/ticket/4872#comment:2

Я прокомментировал, могу ли я разбудить кого-нибудь, когда будет исправление. Радости развития сообщества: P

Ответ 6

Как использовать удаление, получение и обновление, чтобы фиксировать все изменения и отправлять их на сервер в виде массива?

Демо: http://jsfiddle.net/r2d3/p3J8z/

$(function(){

    /* Here we will store all data */
    var myArguments = {};   

    function assembleData(object,arguments)
    {       
        var data = $(object).sortable('toArray'); // Get array data 
        var step_id = $(object).attr("id"); // Get step_id and we will use it as property name
        var arrayLength = data.length; // no need to explain

        /* Create step_id property if it does not exist */
        if(!arguments.hasOwnProperty(step_id)) 
        { 
            arguments[step_id] = new Array();
        }   

        /* Loop through all items */
        for (var i = 0; i < arrayLength; i++) 
        {
            var image_id = data[i]; 
            /* push all image_id onto property step_id (which is an array) */
            arguments[step_id].push(image_id);          
        }
        return arguments;
    }   

    /* Sort images */
    $('.step').sortable({
        connectWith: '.step',
        items : ':not(.title)',
        /* That fired first */    
        start : function( event, ui ) {
            myArguments = {}; /* Reset the array*/  
        },      
        /* That fired second */
        remove : function( event, ui ) {
            /* Get array of items in the list where we removed the item */          
            myArguments = assembleData(this,myArguments);
        },      
        /* That fired thrird */       
        receive : function( event, ui ) {
            /* Get array of items where we added a new item */  
            myArguments = assembleData(this,myArguments);       
        },
        update: function(e,ui) {
            if (this === ui.item.parent()[0]) {
                 /* In case the change occures in the same container */ 
                 if (ui.sender == null) {
                    myArguments = assembleData(this,myArguments);       
                } 
            }
        },      
        /* That fired last */         
        stop : function( event, ui ) {                  
            /* Send JSON to the server */
            $("#result").html("Send JSON to the server:<pre>"+JSON.stringify(myArguments)+"</pre>");        
        },  
    });
});

Вот полное объяснение решения: http://r2d2.cc/2014/07/22/jquery-sortable-connectwith-how-to-save-all-changes-to-the-database/

Ответ 7

Чтобы вызвать событие один раз, вы можете использовать метод receive. Он вызывается, когда элемент из списка помещается в другой список.

$( ".selector" ).sortable({
  stop: function( event, ui ) {}
});

Источник: http://api.jqueryui.com/sortable/#event-receive.

Ответ 8

update: function(e, ui) {
    var draggedOut = this !== ui.item.parent()[0] && !$.contains(this, ui.item.parent()[0]);
    var draggedIn = ui.sender !== null;
    var sameList = !draggedOut && !draggedIn;

    if (sameList || draggedIn) {
        // Do stuff
    }
}