![](/img/trans.png)
[英]How to change row order of table using knock out. Either drag and drop or using Up/Down buttons
[英]What is the simplest way to allow a user to drag and drop table rows in order to change their order?
我有一个Ruby on Rails应用程序,我正在编写一个用户可以选择编辑发票的应用程序。 他们需要能够重新分配行的顺序。 现在我在db中有一个索引列,用作默认排序机制。 我刚刚曝光并允许用户编辑它。
这不是很优雅。 我希望用户能够拖放表格行。 我已经使用了Scriptaculous和Prototype,并熟悉它们。 我已经完成了拖放列表,但没有像这样完成表行。 任何人都有任何建议,不仅要重新排序,还要有效地捕获重新订购?
此外,用户现在可以在JS中动态创建新行,因此该行也必须可重新排序。
如果可以使用RJS而不是直接JavaScript来完成加分。
我之前使用过Yahoo User Interface库来执行此操作:
MooTools sortables实际上比script.aculo.us更好,因为它们是动态的; MooTools允许在列表中添加/删除项目。 将新项目添加到script.aculo.us sortable时,您必须销毁/重新创建可排序项以使新项目可排序。 如果列表包含许多元素,那么这样做会有很多开销。 由于这种限制,我不得不从script.aculo.us切换到更轻量级的MooTools,最终对这个决定非常满意。
MooTools使新添加的项目可排序的方法就是:
sortables.addItems(node);
好吧,我做了一些淘洗,并想出了一些似乎主要起作用的东西。
edit.html.erb:
...
<table id="invoices">
<thead>
<tr>
<th>Id</th>
<th>Description</th>
</tr>
</thead>
<tbody id="line_items">
<%= render :partial => 'invoice_line_item', :collection => @invoice.invoice_line_items.sort %>
</tbody>
</table>
<%= sortable_element('line_items', {:url => {:action => :update_index}, :tag => :tr, :constraint => :vertical}) -%>
...
应用程序/控制器/ invoices.rb
...
def update_index
params["line_items"].each_with_index do |id, index|
InvoiceLineItem.update(id, :index => index)
end
render :nothing => true
end
...
重要的部分是:“sortable_element”中的tag =>:tr和params [“line_items”] - 这给出了新的id列表并在drop上触发。
损害:让AJAX调用掉线,我想我更喜欢存储订单并在用户点击“保存”时更新。 在IE上未经测试。
雅虎的界面比我想象的要容易,在不到四个小时的时间内做了一些时髦的工作。
Scriptaculous的sortables好像去,因为它内置的方式。 http://github.com/madrobby/scriptaculous/wikis/sortable
使用Prototype
和Scriptaculous
:
Sortable.create('yourTable', {
tag: 'tr',
handles: $$('a.move'),
onUpdate: function() {
console.log('onUpdate');
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.