ReactiveX / learnrx

A series of interactive exercises for learning Microsoft's Reactive Extensions Library for Javascript.
1.4k stars 292 forks source link

small problem implementing prob 32 #109

Closed andy-dev closed 5 years ago

andy-dev commented 8 years ago

hello, rookie here, trying to implement drag on a small web app, not sure what Im doing wrong (i included the code here because it is just a couple lines of code, nothing fancy in html and css)

JS

(function (global) {
    function dragger(){
        var $sprite = $('.sprite');
        var $spriteContainer = $('.container');

        var spriteMouseDowns = Rx.Observable.fromEvent($spriteContainer, "mousedown")
        var spriteContainerMouseMoves = Rx.Observable.fromEvent($spriteContainer,"mousemove")
        var spriteContainerMouseUps = Rx.Observable.fromEvent($spriteContainer,"mouseup")
        var spriteMouseDrags =
                spriteMouseDowns.
                    map(function(down){
                        return spriteContainerMouseMoves.takeUntil(spriteContainerMouseUps);
                    }).
                    concatAll();

        spriteMouseDrags.forEach(function(dragPoint){
            $sprite.style.left = dragPoint.pageX + "px";
            $sprite.style.top = dragPoint.pageY + "px";
        });
    };
    dragger();
}(window));
andy-dev commented 8 years ago

here is the jsbin link https://jsbin.com/mabejemege/edit?js,output

jest commented 8 years ago

Use this code to update the position of the sprite.

$sprite.css('left', dragPoint.pageX + "px");
$sprite.css('top', dragPoint.pageY + "px");
seanpoulter commented 5 years ago

The problem here is the JQuery selectors are returning a JQuery collection and not an HTMLElement. These don't work in the call to Observable.fromEvent which is going to try and add and remove an event listener.

For this to work you'd have to unwrap the JQuery elements like this:

-         var $sprite = $('.sprite');
+         var $sprite = $('.sprite').get(0);
-         var $spriteContainer = $('.container');
+         var $spriteContainer = $('.container').get(0);

The demo works in JSBin: https://jsbin.com/jigohin/1/edit?js,output


CC: You can close this one @morenoh149. 😉