jquery Sortable connectWith дважды вызывает метод обновления - PullRequest
28 голосов
/ 16 августа 2010

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

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

Ответы [ 8 ]

58 голосов
/ 08 сентября 2011

Ответ от: http://forum.jquery.com/topic/sortables-update-callback-and-connectwith

update: function(e,ui) {
    if (this === ui.item.parent()[0]) {
        //your code here
    }
}
11 голосов
/ 10 октября 2013

Ответ Стефана был хорош, но в нем не упоминается еще одна часть головоломки, поэтому вот она - на случай, если кто-то (как я) не поймет ее сразу.Это должно позволить вам обработать все это в функции 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
        }
    }
}
6 голосов
/ 12 января 2012

Попробуйте это:

update: function(e,ui) {
    if (!ui.sender) {
        //your code here
    }
}
4 голосов
/ 20 марта 2011

Вы должны использовать событие приема (http://jqueryui.com/demos/sortable/#event-receive).

Проверьте разрешение в самом низу на http://bugs.jqueryui.com/ticket/3178.

2 голосов
/ 22 июля 2014

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

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

<code>$(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's fired first */    
        start : function( event, ui ) {
            myArguments = {}; /* Reset the array*/  
        },      
        /* That's fired second */
        remove : function( event, ui ) {
            /* Get array of items in the list where we removed the item */          
            myArguments = assembleData(this,myArguments);
        },      
        /* That's 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's fired last */         
        stop : function( event, ui ) {                  
            /* Send JSON to the server */
            $("#result").html("Send JSON to the server:<pre>"+JSON.stringify(myArguments)+"
"); }, }); });

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

2 голосов
/ 04 марта 2011

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

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

1 голос
/ 09 апреля 2015

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

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

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

0 голосов
/ 10 мая 2017
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
    }
}
...