RXJS拖拽

时间:2015-05-06 15:05:19

标签: drag-and-drop rxjs

这个问题与RXJS有关。我正在尝试调整github中的拖放示例,以便为一类div而不仅仅是单个元素ID。 https://github.com/Reactive-Extensions/RxJS/blob/master/examples/dragndrop/dragndrop.html

简单的更改为div提供类或ID不起作用,我失去了拖动元素的能力

3个简单的改变:

HTML line 7 i.e. <div class="dragTarget">Drag Me!</div>
CSS line 1 i.e. .dragTarget { style attributes unchanged }
JS line 4 i.e var dragTarget = document.getElementsByClassName('dragTarget');

我不熟练知道这是否是RXJS中的错误,或者该示例不够通用。有关RXJS事件的文件表明这些变化应该足够了。任何帮助赞赏。感谢。

1 个答案:

答案 0 :(得分:4)

fromEvent将使用您传递的任何对象的onoff方法,否则将使用addEventListenerremoveEventListener。因此,如果你正在使用jQuery,你可以简单地选择所有这些并使用它(例如Observable.fromEvent($('.targetNode'), 'mouseup'))。

否则,您可以使用onoff方法的任何对象订阅或取消订阅活动,例如我在下面做的。

除此之外,您可以在每个流中获得的target个对象上使用MouseEvent属性来获取您想要移动的实际DOM节点...

下面的示例应该可以解决这个问题。

(function (global) {

  /**
    selectNodes is a method to select a NodeList, but convert it to 
    a type that has `on` and `off` methods RxJS 2 expects to see for `fromEvent`
  */
  function selectNodes(selector) {
    var nodes = document.querySelectorAll(selector);

    return {
      // the selected nodes
      nodes: [].slice.call(this.nodes),

      // subscribe to an event on every selected node
      on: function(eventName, handler) {
        this.nodes.forEach(function(node) { node.addEventListener(eventName, handler); });
      },

      // unsubscribe from the event on every selected node
      off: function(eventName, handler) {
        this.nodes.forEach(function(node) { node.removeEventListener(eventName, handler); });
      }
    };
  }

  function main () {
    // IMPORTANT CHANGE: Use the selectNodes method we made
    var dragTargets = selectNodes('.dragTarget');

    // Get the three major events
    var mouseup   = Rx.Observable.fromEvent(dragTargets, 'mouseup');
    var mousemove = Rx.Observable.fromEvent(document,   'mousemove');
    var mousedown = Rx.Observable.fromEvent(dragTargets, 'mousedown');

    var mousedrag = mousedown.flatMap(function (md) {

      // calculate offsets when mouse down
      var startX = md.offsetX, startY = md.offsetY;

      // Calculate delta with mousemove until mouseup
      return mousemove.map(function (mm) {
        mm.preventDefault();

        return {
          left: mm.clientX - startX,
          top: mm.clientY - startY,
          target: mm.target, // IMPORTANT CHANGE: the element you care about
        };
      }).takeUntil(mouseup);
    });

    // Update position
    var subscription = mousedrag.subscribe(function (d) {
      d.target.style.top = d.top + 'px';
      d.target.style.left = d.left + 'px';
    });
  }

  main();

}(window));