Next/Previous navigation of an Observable
Ad
I have an observable of blog posts, converted from an array:
let posts = Rx.Observable.fromArray(blogPosts)
And two observables nextClicks
and prevClicks
of button click events for next/previous navigate respectively:
What I want is:
- Initially the
posts
observable emits the very first post and then wait for click events posts
emits next post whennextClicks
emits (repeat current post if no next available)posts
emits prev post whenprevClicks
emits (repeat current post if no prev available)
And I'm not sure if this is possible:
- Two observables
postNextable
andpostPrevable
, derived fromposts
, indicating whether there is a next/prev post available inposts
respectively
Thanks in advance!
Ad
Answer
Ad
There are several ways to do 1, 2, 3 and 4. For number 4, I wonder how you plan to use those observables.
One way which only uses pure functions and no subjects is :
var blogPosts$ = Rx.Observable.just(blogPosts);
var index$ = Rx.Observable.merge(nextClicks, prevClicks)
.withLatestFrom(blogPosts$, function(ev, blogPosts){return {posts: blogPosts, ev : ev};})
.scan(function(index, posts_and_ev){
return isNextClick(posts_and_ev.ev) && isNextable(posts_and_ev.posts, index) ? index + 1
:isPrevClick(posts_and_ev.ev) && isPrevable(posts_and_ev.posts, index) ? index - 1
:index
}, 0);
var currentPost$ = index$.withLatestFrom(blogPosts$, function (index, blogPost){return blogPost[index]; }).startWith(blogPosts[0]);
var postNextable = index$.withLatestFrom(blogPosts$, function (index, blogPost){return isNextable(blogPost, index);});
var postPrevable = index$.withLatestFrom(blogPosts$, function (index, blogPost){return isNextable(blogPost, index);})
The output you seek is named here currentPost$
.
Code test included thereafter. isNextable
, isNextClick
, isPrevable
, isPrevClick
have obvious semantics, and are easy to write (for example discriminating on key codes or button ids or else for your next
and prev
events). sample code
Ad
source: stackoverflow.com
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad