ngAfterViewInit():any {

        const container = this.containerElement.nativeElement;
        const draggable = this.draggableElement.nativeElement;

        const mouseDown$ = Observable.fromEvent(draggable, "mousedown");
        const mouseMove$ = Observable.fromEvent(container, "mousemove");
        const mouseUp$ = Observable.fromEvent(container, "mouseup");

        const drag$ = mouseDown$
            .map(() => mouseMove$
                .filter(event => boundaryCheck(event))
                .takeUntil(mouseUp$))
            .concatAll();

        drag$.subscribe( (event: MouseEvent) => {
                this.renderer.setElementStyle(draggable, 'left', event.clientX - (draggableWidth / 2) + "px");
                this.renderer.setElementStyle(draggable, 'top', event.clientY - (draggableHeight / 2) + "px");
            },
            error => console.log('error')
        );

        function boundaryCheck(event) {

            const leftBoundary = container.offsetLeft + (draggableWidth / 2);
            const rightBoundary = container.clientWidth + container.offsetLeft - (draggableWidth / 2);
            const topBoundary = container.offsetTop + (draggableHeight / 2);
            const bottomBoundary = container.clientWidth + container.offsetTop - (draggableHeight / 2);

            return event.clientX > leftBoundary &&
                event.clientX < rightBoundary &&
                event.clientY > topBoundary &&
                event.clientY < bottomBoundary;
        }
    }
Example #2
0
    ngAfterViewInit() {
        const down = Observable.fromEvent(this.down.nativeElement, 'click')
        const up = Observable.fromEvent(this.up.nativeElement, 'click')

        this.counter = down
            .mapTo(-1)
            .merge(up.mapTo(1))
            .startWith(0)
            .scan<number>((prev, cur) => prev+cur, 0)

        down
            .buffer(down.debounceTime(250))
            .map(clicks => clicks.length)
            .filter(length => length == 2)
            .subscribe(
                (val) => console.log('doubleclick', val),
                (err) => console.error(err),
                () => console.log('complete')
            )

        // down
        //     .bufferTime(250)
        //     // .filter((clicks:any[]) => clicks.length > 1)
        //     .subscribe((val) => {
        //         console.log('buff', val);
        //     })
    }
Example #3
0
  initSearchInput() {
    var keyups = Observable.fromEvent($("#search"), "keyup")
      .map(event => event.target.value)
      .filter(term => term.length > 2)
      .debounceTime(400)
      .distinctUntilChanged()
      .flatMap(this._spotifyService.searchArtists);

    var subscription = keyups.subscribe(result => console.log(result));
    // To unsubscribe from notifications:
    // subscription.unsubscribe();

    // var debounced = _.debounce(text => {
    //   var url = `https://api.spotify.com/v1/search?type=artist&q=${text}`;
    //   $.getJSON(url, artists => {
    //     console.log(artists);
    //   });
    // }, 400);
    //
    // $("#search").keyup(e => {
    //   var text = e.target.value;
    //   if (text.length < 3) return;
    //   debounced(text);
    // });
  }
Example #4
0
 ngAfterViewInit() {
     
      var keyups = Observable.fromEvent($('#search'),'keyup')
      .map(e => (Object(Object(e).target)).value)
      .filter(text => text.length > 3)
      .debounceTime(400)
      .distinctUntilChanged()
      
      keyups.subscribe(data => console.log(data));
     
     // $("#search").keyup(function (e) {
     //     var text = e.target.value;
     //     var debounce = _.debounce(function (text) {
     //         var url = 'https://api.spotify.com/v1/search?type=artist&q=' + text;
     //         $.getJSON(url, function (artist) {
     //             console.log(artist);
     //         })
     //     }, 400)
     //     if (text.length < 3)
     //         return;
     //     debounce(text);
     // })
     
     
 }
  registerWatchingSubscriptionsAfterInitializeOnInit() {
    let previousTime: number;
    let previousKeyCode: number;

    // 次回ページ遷移入時にunsubscribeするsubscription群。
    this.service.SC.disposableSubscriptions = [
      // キーボード入力イベントをハンドリングする。Storeにデータを送る。
      Observable.fromEvent<KeyboardEvent>(document.querySelector('sg-page4 #keyinput'), 'keyup')
        // .do(event => console.log(event))
        .do(event => { // keyAが押されると処理開始。          
          if (!this.proccessing && event.keyCode === 65 /* keyA */) {
            previousTime = this.startTimer();
            previousKeyCode = 64;
          }
        })
        .do(event => { // 処理中のキー入力イベントをハンドリングする。
          if (this.proccessing) {
            const keyCode = event.keyCode;
            if (keyCode - previousKeyCode !== 1) {
              toastr.error('OOPS! TRY AGAIN.'); // alert('OOPS! TRY AGAIN.');
              this.stopTimer();
            } else {
              const now = lodash.now();
              const keyInput: KeyInput = {
                code: event['code'],
                keyCode: keyCode,
                filterId: this.filterId,
                diff: keyCode === 65 /* keyA */ ? 0 : now - previousTime
              };
              this.service.putKeyInput(keyInput).then(x => x.log('KeyInput')); // serviceを経由してStoreに値を送り、戻り値として得たStateをコンソールに出力する。
              previousTime = now;
              previousKeyCode = keyCode;
            }
          }
        })
        .do(event => { // keyZが押されると処理終了。
          if (this.proccessing && event.keyCode === 90 /* keyZ */) {
            this.stopTimer(true);
          }
        })
        .subscribe(() => this.cd.markForCheck()),

      // Storeからデータを受け取ってグラフを更新する。キーボード入力がトリガーとなりリアルタイムに更新される。
      this.state.keyInputs$
        .map(objs => objs.reverse()) // 降順を昇順に反転
        .do(objs => {
          if (objs.filter(obj => 'diff' in obj && 'code' in obj).length > 0) {
            const diffs = objs.map(obj => obj.diff / 1000); // diffの単位をミリ秒から秒に変換。
            const letters = objs.map(obj => obj.code.charAt(3)); // ex)'KeyA'から'A'を取り出す。
            this.chart.load({ // c3のグラフを更新する。
              columns: [
                ['diff_time', ...diffs]
              ],
              categories: letters,
            });
          }
        })
        .subscribe(),
    ];
  }
    constructor() {
        //Using Reactive Extensions and Observables
        var keyups = Observable.fromEvent($("#artistSearch"),"keyup")
            .map(e => e.target.value)
            .filter(text => text.length >= 3)
            .debounceTime(400)
            .distinctUntilChanged();
        
        keyups.subscribe(data => console.log(data));
        
        //Bad implementation (using jQuery:
        // var debounced = _.debounce(function (text) {
        //     var url = "https://api.spotify.com/v1/search?type=artist&q=" + text;
        //     $.getJSON(url, function (artists) {
        //         console.log(artists);
        //     });
        // }, 400);

        // $("search").keyup(function (e) {
        //     var text = e.target.value;
        //     if (text.length < 3)
        //         return;
        //     debounced(text);
        // });
    }
  ngOnInit() {
    const uid = this.store.currentUser.uid;

    /* URLからidを取得する */
    this.store.disposable = this.params$.pluck<string>('id')
      .do(noteid => {
        if (noteid) {
          /* 保存済みnoteを呼び出す */
          this.store.disposable = this.service.readNote$(noteid)
            .do(note => {
              this.note = note;
              this.oldNote = lodash.cloneDeep(this.note);
              this.cd.markForCheck();
            })
            .subscribe();
        } else {
          /* noteを新規作成 */
          this.note = this.service.createNote();
          this.oldNote = lodash.cloneDeep(this.note);
          this.cd.markForCheck();
        }
      })
      .subscribe();

    /* キー入力がある度にnoteを保存する */
    this.store.disposable = Observable.fromEvent<KeyboardEvent>(this.el.nativeElement, 'keyup')
      .debounceTime(1000)
      .do(() => {
        this.service.writeNote(this.note, this.oldNote);
      })
      .subscribe();
  }
    constructor() {
    
    //Observables version
    var keyups = Observable.fromEvent($("#search"),"keyup");
    //keyups.subscribe( data => console.log(data) );



         //callback hell version without observables
        /*var debounced = _.debounce(function (text) {
            var url = "https://api.spotify.com/v1/search?type=artist&q=" + text;
            $.getJSON(url, function (artists) {

                console.log(artists);


            })
        }, 400);

        $("#search").keyup(function (e: any) {
            var text = e.target.value;

            //check for input length
            if (text.length < 3)
                return;

            debounced(text);

        });*/
    }
 jQuery.getJSON(url, ()=> {
     var path = `https://${source}/Snapshots/business${businessId}/station${stationId}/${fileName}.jpg`;
     jQuery(this.elRef.nativeElement).find('.newImage').fadeOut(200);
     var img = this.renderer.createElement(this.elRef.nativeElement, 'img', null);
     jQuery(img).addClass('snap');
     var int$ = Observable.interval(500).do(()=> {
         img.src = path;
     })
     var $err = Observable.fromEvent(img, 'error').do(()=>{
         jQuery(this.elRef.nativeElement).find('.snap').remove();
     })
     var load$ = Observable.fromEvent(img, 'load')
     var subscription = Observable.merge(int$, $err).takeUntil(load$).delay(500).subscribe((res)=> {
         subscription.unsubscribe();
     })
 });
    constructor(){
        var keyups = Observable.fromEvent($("#search"), "keyup") // subscribe to keyups.
            .map(e => e.target.value) // map from DOM event to string
            .filter(s => s.length >= 3) // filter for only strings >= 3
            .debounceTime(400) // debounce for 400ms
            .distinctUntilChanged() // call only once per input.
            .flatMap(s => {
                var url = "https://api.spotify.com/v1/search?type=artist&q=" + s;
                var promise = $.getJSON(url); // get the promise from getJSON
                return Observable.fromPromise(promise); // subscribe to the promise
            }); // flatMap flattens our Observable of Observables
            // into an Observable which returns the data.
            // In production, the code inside flatMap should be refactored into a service class.

        var subscription = keyups.subscribe(data => console.log(data));
        // subscription.unsubscribe(); // to stop receiving events.

        // // Create a debouncer, so the max freq we call server is 400ms.
        // var debounced = _.debounce(function(text){
        //     var url = "https://api.spotify.com/v1/search?type=artist&q=" + text;
        //     $.getJSON(url, function(artists) {
        //         console.log(artists);
        //     });
        // }, 400);

        // $("#search").keyup(function(e){
        //     var text = e.target.value;

        //     // To not flood server.
        //     if(text.length < 3)
        //         return;

        //     debounced(text);
        // });
    }
 constructor(){
     var keyups=Observable.fromEvent($("#search"), "keyup")
         .map(e => e.target.value)
         .filter(text => text.length >=3)
         .debounceTime(400)
         .distinctUntilChanged()
         .flatMap(searchTerm => {
                 var url="https://api.spotify.com/v1/search?type=artist&q="+searchTerm;
                 var promise = $.getJSON(url);
                 return Observable.fromPromise(promise);
         });
     keyups.subscribe(data => console.log(data));
    
 //     var debounced = _.debounce(function(text){
 //          var url="https://api.spotify.com/v1/search?type=artist&q="+text;
 //         $.getJSON(url, function (artists) {
 //             console.log(artists);
 //         })
 //     }, 400)
 //     $('#search').keyup(function (e) {
 //         var text=e.target.value;
 //         if (text.length<3)
 //             return;
 //        debounced(text);
 //     })
 // }
 }
    constructor(){
//Observable way - apply operators to add some logic
      var keyups = Observable.fromEvent($("#search"), "keyup") // reactivex.io
        .map(e=>e.target.value)
        .filter(text => text.length >=3)
        .debounceTime(400)
        .distinctUntilChanged()
        .flatMap(searchTerm => {//flatens out the new observable so its not an observ in an observ
          var url = "https://api.spotify.com/v1/search?type=artist&q=" + searchTerm;
          var promise = $.getJSON(url);
          return Observable.fromPromise(promise);
        });//better to put in a service -> spotifyService.searchArtists
      var subsciption = keyups.subscribe(data => console.log(data));
      // subsciption.unsubscribe();//used to cancel



// Callback way
      // var debounced = _.debounce(function(text){
      //   var url = "https://api.spotify.com/v1/search?type=artist&q=" + text;
      //   $.getJSON(url, function(artist){
      //     console.log(artist);
      //   });
      // }, 400)
      //
      // $("#search").keyup(function(e){
      //   var text = e.target.value;
      //
      //   if(text.length < 3)
      //     return;
      //
      //   debounced(text);
      //
      // });
    }
    connect() {
        this.socket_ = io.connect("/chatroom", { reconnection: false });
        this.socket_.on("error", (err) => { console.log(err); });

        this.socket_.on("disconnect", () => { this.events_.emit("socket-disconnect"); });

        this.chat$ = Observable.fromEvent(this.socket_, "chat");
        this.whisper$ = Observable.fromEvent(this.socket_, "whisper");

        let userAction$ = new Observable<UserAction>(observer => {
            this.socket_.on("user-action", (action) => observer.next(action));
        });

        this.userList$ = new Observable<UserAction>(observer => {
            this.socket_.on("user-list", data => observer.next(data));
            this.socket_.on("list-completed", () => observer.complete());
        }).concat(userAction$);
    };
Example #14
0
  constructor(private notificationService: NotificationService) {
    this.subject = new Subject();
    this.store = store;
    this.trigger();

    Observable.fromEvent(window, 'resize').debounceTime(100).map(()=>{
      this.trigger()
    }).subscribe()
  }
Example #15
0
	attachEvent (newContainer: Window | ElementRef | any) {
		this.clean();
		this.container = newContainer;
		if (newContainer) {
			const throttle: number = this.infiniteScrollThrottle;
			this.disposeScroll = Observable.fromEvent(this.container, 'scroll')
				.debounce(ev => Observable.timer(throttle))
				.subscribe(ev => this.handler())
		}
	}
 static listenForBreaks(): Observable<{}> {
   if(! ResponsiveService.WINDOW$ ){
     ResponsiveService.WINDOW$ = Observable
                                   .fromEvent( window, 'resize' )
                                   .debounce( () => Observable.interval(200) )
                                   .map( e => {
                                     return this.getCurrentBreak();
                                   } );
   }
   return ResponsiveService.WINDOW$;
 }
  private _bindListeners() {
    console.log('should listen for incoming events');
    // this.prob = Observable.fromEvent(this.io, 'probe:single');
    // this.bid = Observable.fromEvent(
    //   this._io, 'auction:new:bid'
    // ).share();

    let probeSource = Observable.fromEvent(
      this._io, 'bid:probe'
    )
    let bidSource = Observable.fromEvent(
      this._io, 'auction:new:bid'
    )

    this.bid = Observable.merge(probeSource, bidSource);

    this.bidder = Observable.fromEvent(
      this._io, 'bidder:joined:auction'
    ).share();
  }
    ngOnInit() {

        var button = document.querySelector('#buttond');
        Observable.fromEvent(button, 'click')
        // scan (reduce) to a stream of counts
        .scan(count => count + 1, 0)
        // Set the count on an element each time it changes
        .subscribe(count =>
         document.querySelector('#count').innerHTML = count.toString());
        console.log("Initialization of the component");
    }
  ngAfterViewInit(){

		const box_element = document.getElementById("box");
		const mouseup_event = Rx.Observable.fromEvent(box_element, 'mouseup');
		const mousemove_event = Rx.Observable.fromEvent(box_element, 'mousemove');
		const mousedown_event = Rx.Observable.fromEvent(box_element, 'mousedown');

		const source = mousedown_event.flatMap( (event : MouseEvent) => {
			
			let start_pageX = event.pageX;
			let start_pageY = event.pageY;
			let start_left = box_element.offsetLeft;
			let start_top = box_element.offsetTop;
			console.log("start x" , start_pageX , 'start y' , start_pageY);
			console.log("start box left" , start_left , 'start box top' , start_top);
			box_element.className = "hovering";

			return mousemove_event.map((e : MouseEvent)=>{
				console.log("mouse x" , e.pageX , "mouse y" , e.pageY)
				return {
					left: start_left + (e.pageX - start_pageX),
					top: start_top + (e.pageY - start_pageY)
				};
			}).takeUntil(mouseup_event);
		});

		mouseup_event.subscribe(
			()=>{
				box_element.className = null;
			}
		);
		source.subscribe((pos)=>{
			console.log("pos X" , pos.left , "pos y" , pos.top);
			console.log("left", box_element.style.left , "top", box_element.style.top  )
			box_element.style.left = String(pos.left) + "px";
			box_element.style.top = String(pos.top) + "px";
			console.log("---------------");
		})

  }
    constructor(myElement: ElementRef, private http: Http) {
        var keyups = Observable.fromEvent(myElement.nativeElement, "keyup")
            .map(e => e.target.value)
            .filter(x => x.length > 3)
            .debounceTime(400)
            .distinctUntilChanged()
            .flatMap(searchTerm => {
                var url = 'https://api.spotify.com/v1/search?type=artist&q=' + searchTerm;
                return this.http.get(url);
            });

        var subscribtion = keyups.subscribe((data: Response) => { console.log(this.extractData(data)); });
        // subscribtion.unsubscribe();
    }
Example #21
0
const createRxSocket = (connection) => {
  let messages = Rx.Observable.fromEvent(connection, 'message', (message) => JSON.parse(message));
  let messageObserver:any = {
    next(message){
      if(connection.readyState === 1){
        connection.send(JSON.stringify(message));        
      }
     }
  }
  connection.on('close', () => {
    connection.streams && connection.streams.forEach(s => s.unsubscribe());
  })
  return Rx.Subject.create(messages, messageObserver);
}
 constructor(){
     //this.jqueryImplementation();
     var keyups = Observable.fromEvent($("#search"), "keyup")
         .map(e=>e.target.value)
         .filter(text=>text.length >= 3)
         .debounceTime(400)
         .distinctUntilChanged()
         .flatMap(text=>{
             var url = "https://api.spotify.com/v1/search?type=artist&q="+text;
             var promise = $.getJSON(url);
             return Observable.fromPromise(promise);
         });
     keyups.subscribe(data => console.log(data));
 }
  ngOnInit() {
    this.store.disposable = this.service.readUserData()
      .do(userData => {
        this.name = userData.name || '';
        this.cd.markForCheck();
      })
      .subscribe();

    this.store.disposable = Observable.fromEvent<KeyboardEvent>(this.el.nativeElement, 'keyup')
      .debounceTime(100)
      .do(() => {
        this.writeUserData();
      })
      .subscribe();
  }
  constructor(public processorService: ProcessorService,
              private el: ElementRef) {

    processorService.fields
      .subscribe(
        fields => this.fields = fields,
        err => console.error('Error ' + err)
      );

    const eventStream = Observable.fromEvent(el.nativeElement, 'keyup')
      .map((e: any) => e.target.value) // extract the value of the input
      .filter((text: string) => text.length > 0) // filter out if empty
      .debounceTime(400);

    eventStream.subscribe(input => this.processorService.processSum(this.fields));
  }
    constructor(){
    	var keyups = Observable.fromEvent($("#search"),"keyup")
    	.map(e => e.target.value)
    	.filter(text => text.length >= 3)
    	.debounceTime(300)
    	.distinctUntilChanged()
    	.flatMap(searchTerm => {
    		var url = "https://api.spotify.com/v1/search?type=artist&q=" + searchTerm;
    		var promise = $.getJSON(url);
    		return Observable.fromPromise(promise);
//move code in flatMap to a service
    	});

    	var subscription = keyups.subscribe(data => console.log(data));

    	//subscription.unsubscribe();
    }
  ngOnInit() {
      this.val = this.el.nativeElement.value;
      
      Observable.fromEvent(this.el.nativeElement, 'input')
          .map((val:Event) => val.target)
          .subscribe((val:HTMLInputElement) => {
              this.val = this.filter(val.value);
              
              if(this.val != val.value) {
                  let selectionStart = val.selectionStart;
 
                  val.value = this.val;
              
                  val.selectionStart = selectionStart;
                  val.selectionEnd = selectionStart;
              }
          });
  }
    constructor() {

        var keyups = Observable.fromEvent($("#search"), "keyup");
        keyups.subscribe(data=>console.log(data));

        // var debounced = _.debounce(function (text) {
        //     var url = "https://api.spotify.com/v1/search?type=artist&q=" + text;
        //     $.getJSON(url, function (artists) {
        //         console.log(artists);
        //     });
        // }, 400);
        //
        // $('#search').keyup(function (e) {
        //     var text = e.target.value;
        //     if (text.length < 3)
        //         return;
        //     debounced(text);
        // });
    }
    getList(name:string):Observable<List> {
        let obs$: Observable<List>;

        if (this._lists.hasOwnProperty(name)) {
            obs$ = Observable.of(this._lists[name]);
        } else {
            let dsList = this._deepstream.record.getList(name);
            this._lists[name] = new List(this._deepstream, dsList);

            obs$ = Observable.fromEvent(dsList, "ready")
                .map(r => this._lists[name]);
        }

        (obs$ as any).getEntries = () => {
            return obs$.flatMap(list => {
                return list.getEntries();
            });
        };
        return obs$;
    }
  registerWatchingSubscriptionsAfterInitializeOnInit() {
    // 次回ページ遷移入時にunsubscribeするsubscription群。
    this.service.SC.disposableSubscriptions = [
      Observable.fromEvent<KeyboardEvent>(document.querySelector('sg-page1 #title'), 'keyup')
        .debounceTime(100)
        .do(() => this.service.putTitle(this.title).then(x => x.log('Title')))
        .subscribe(),

      this.state.titles$
        .do(titles => console.log('DetectChange: ' + titles[2] + ' -> ' + titles[1] + ' -> ' + titles[0] + ' on Page1'))
        .do(titles => this.title = titles[0])
        .subscribe(),

      this.state.titleReplayStream$$
        .do(title => this._$title = title)
        .subscribe(() => this.cd.markForCheck()),

      this.state.colorsReplayStream$$
        .do(colors => this._$colors = colors)
        .subscribe(() => this.cd.markForCheck()),
    ];
  }
 constructor(){
     var keyups = Observable.fromEvent($('#search'),"keyup")
     .map( e => e.target.value) // transform elements to different object.
     .filter( text => text.length >= 3) // filter or conditions
     .debounceTime(400) // pause time for avoid not call more times. wait 400s.
     .distinctUntilChanged() // same input not call. if left and right arrow press.
     .flatMap( searchTerm =>
     {
        var url = "https://api.spotify.com/v1/search?type=artist&q="+searchTerm;
        var promise = $.getJSON(url);
        return Observable.fromPromise(promise); // promise is done. json get from server and push it to Observable.
     }); // Transforming input 
     // Use flatMap merge many Observable to one. 
    var subscribe =  keyups.subscribe( data => console.log(data));
    subscribe.unsubscribe(); // Help in real word app to user turn off multiple notifications.       
     
     // var debounced =  _.debounce(function(text){
     //     var url = "https://api.spotify.com/v1/search?type=artist&q="+text;
     //     $.getJSON(url, function(artists){
     //         console.log(artists);
     //     })
     // }, 400);
     // $('#search').keyup(function(e){
     //     var text = e.target.value;
     //     if(text.length < 3)
     //         return;
              
     //    debounced(text);
     // });
     
     //  $('#search').keyup(function(e){
     //      var text = e.target.value;
     //      console.log(text);
     //  });   
          
 }