使用JQuery UI时遇到问题。我想要实现的是:


我有一个带有对象的可排序列表(.form_container)。当它们的位置改变时,ajax调用将更新数据库。
在此列表之外,我有“文本项”(.create_item)。当这些项目被放到可排序列表上时,我想进行一次ajax调用,该调用将为我提供内容,以便将简单的项目转换为对象。
然后,因为添加了新对象,所以我希望ajax调用位置被触发。但是在正确加载新对象之前没有。


我希望我足够清楚...

所以首先,我虽然要做类似的事情

第一次尝试 :

$(".create_item").draggable({
  containment: 'window',
  connectToSortable: ".form_container",
  helper: "clone",
});
$(".form_container").droppable({
  accept: ".create_item",
  tolerance: 'fit',
  over: function(event,ui) {
    // Something here
  },
  drop: function(event,ui) {
    // Ajax calls that changes my item into an object
  }
});
$(".form_container").sortable({
  axis: "y",
  containment: ".form_container",
  revert: true,
  update: function(event, ui){
    // Ajax calls that update positions in DB
  }
});


问题是,connectToSortable还会触发放置事件,因此该事件被调用两次,从而引起麻烦。

因此,我遵循了某人关于SOF的建议,并针对类似的内容更改了我的代码。

第二次尝试 :

$(".create_item").draggable({
  containment: 'window',
  connectToSortable: ".form_container",
  helper: "clone",
});
$(".form_container").droppable({
  accept: ".create_item",
  tolerance: 'fit',
  over: function(event,ui) {
    // Something here
  }
  // No more drop function
});
$(".form_container").sortable({
  axis: "y",
  containment: ".form_container",
  revert: true,
  update: function(event, ui){
    // Ajax calls that update positions in DB
  },
  receive: function(event,ui) {
    // Ajax calls that changes my item into an object
  }
});


问题是,在接收事件完成之前触发了更新事件,并且我的项目尚未正确转换为漂亮的对象。

那就是一切,有人可以帮我吗?

最佳答案

就您的首次尝试而言,据我所知,两次挂断是已知问题(http://url.ba/o88p)。我只能通过声明一些全局变量(计数器)来提出一些解决方法,然后每隔第二次使用它进行调用:

  drop: function(event,ui) {
    if (counter++%2) {
        // Ajax calls that changes my item into an object
    }
  }


关于您的第二次尝试,我认为解决方案有点优雅。首先,使用bind声明您的更新方法(只有以这种方式绑定它才能手动触发它)。

var _updateFunction = function(event, ui){
    // logic for update, ajax calls, etc.
};
$('.form_container').bind('sortupdate', _updateFunction);


现在,创建接收的函数,如下所示:

receive: function(event,ui) {
    // don't let update be called
    $('.form_container').unbind('sortupdate');

    $
      // call to create object using ajax
      .ajax()
      // when this call is finished
      .done(function() {
          $('.form_container')
              .bind('sortupdate', _updateFunction)
              .trigger('sortupdate');
      })
}


这是jsfiddle http://jsfiddle.net/7jPAv/中的示例

关于jquery - jQuery UI:可排序-我应该使用哪个事件?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/6828387/

10-09 16:52
查看更多