Drag-and-Drop 拖放
The ability to grab an element with the mouse, move it, and release it somewhere else is familiar in desktop applications but rarer in web browsers. This is because coding such behavior in plain JavaScript is very complicated. Fortunately, it requires only one line in symfony.在桌面应用中用鼠标将一个元素拖放到某个地方是很常见的, 但在浏览器中却极少见. 这是因为用Javascript编写这些行为是非常复杂的. 但是在symfony中却非常幸运地只要用一行就可以实现.
框架提供了两个辅助函数: draggable_element() 和drop_receiving_element(), 它们可以被看成是行为修改器(modifier), 他们将发现器(observer)和能力加给相应的元素. 用它们可以将可拖放的元素声明为可拖放的draggable或接收receiving 元素. 一个可拖放元素就是能用鼠标点击抓取的元素, 只要鼠标按钮未松开, 这个元素就可以在整个窗口中移动. 当一个可拖放元素被松开, 一个接收元素就调用一个远程函数. 表11-32显示了用一个购物车接收元素进行交互的例子.
表11-32 购物车中的可拖放元素和”放下-接收”元素
[php]
<ul id="items">
<li id="item_1" class="food">Carrot</li>
<?php echo draggable_element('item_1', array('revert' => true)) ?>
<li id="item_2" class="food">Apple</li>
<?php echo draggable_element('item_2', array('revert' => true)) ?>
<li id="item_3" class="food">Orange</li>
<?php echo draggable_element('item_3', array('revert' => true)) ?>
</li>
<div id="cart">
<p>Your cart is empty</p>
<p>Drag items here to add them to your cart</p>
</div>
<?php echo drop_receiving_element('cart', array(
'url' => 'cart/add',
'accept' => 'food',
'update' => 'cart',
)) ?>
无序列表中的每一项都可以被鼠标拖动并在整个窗口中移动. 鼠标松开时, 它们将返回开始的位置. 如果在’cart’元素上松开鼠标, 它就触发一个调用cart/add动作的远程函数. 这个动作根据id请求参数确定该将哪个项目放进cart元素.表11-32模拟了一次真正的购物会话: 你可以抓取所需项目放进购物车, 然后结帐.
TIP In Listing 11-32, the helpers are written just after the element they modify, but that is not a requirement. You could very well group all the draggable_element() and drop_receiving_element() helpers at the end of the template. The important thing is the first argument of the helper call, which specifies the identifier of the element to receive the behavior.在表11-32中, 辅助函数正好写在要改变的元素的后面, 但这不是必须的.你可以在模板的最后将draggable_element()和drop_receiving_element()分组列出. 重要的是不是辅助函数调用的第一个参数, 它将指明要接受行为的元素标识符.
draggable_element()辅助函数接受如下参数:
revert: 如果为真, 当释放鼠标时,元素将返回原来位置.它也可以是任意的函数指针, 用于拖动结束时调用.
ghosting: 克隆一个元素并且拖动这个复制品, 放下这个复制品之前, 原先的元素留在原来的地方不动.
snap: 如果为假, 则不会出现快照.否则,可拖动元素只能被拖拽到由xy 或 [x,y] 或function(x,y){ return [x,y] }指定的xy交叉点.
drop_receiving_element() 辅助函数接受如下参数:
accept: 描述CSS类的一个字符串或一个字符串数组. 只有当可拖放元素有一个或多个CSS类时, 才能被接受..
hoverclass: 当用户在一个元素上拖动一个被接受的可拖动元素, 则将CSS类加到这个元素上.