rxjs test

by shapeshifta

HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/rxjs/5.5.2/Rx.js"></script>
<ul class="pagination">
</ul>
<div id="count"></div>

<div id="hello"></div>

CSS

.disabled {
  pointer-events: none;
  background: red;
}

.pagination li {
  display: inline-block;
  list-style: none
}

.pagination a {
  color: black;
  float: left;
  padding: 8px 16px;
  text-decoration: none;
  transition: background-color .3s;
}

.pagination a.active {
  background-color: #4CAF50;
  color: white;
  pointer-events: none;
}

.pagination a:hover:not(.active) {
  background-color: #ddd;
}

Babel + JSX

function render(pagination) {
  let { activePage, pages } = pagination;
  // convert pages to an array
  pagesArray = Array.from(Array(pages).keys()).map(x => ++x);
  const links = pagesArray.map((page, index) => {
      	return `<li><a href="#" class="${activePage === page ? 'active' : ''}" data-page="${page}">${page}</a></li>`
        }).join('');
  
  return (
      `<li><a href="#" class="${activePage <= 1 ? 'disabled' : ''}" data-page="${activePage - 1}">&lt;</a></li>
      ${links}
      <li><a href="#" class="${activePage >= pages ? 'disabled' : ''}" data-page="${activePage + 1}">&gt;</a></li>`
    );
}

// register observerables
const $pagination = $('.pagination');
const pagination = Rx.Observable.fromEventPattern(
  handler => { $pagination.on('click', 'a', handler); },
  handler => { $pagination.off('click', 'a', handler); })
  .map(event => state => $.extend(true, {}, state, {
  	pagination: {
      activePage: $(event.target).data('page')
    }
  }));
// fake ajax observerable for later (fromPromise)
const ajax = new Rx.Subject();

// We merge all state changes producing observables
const initialState = {
  pagination: {
  	pages: 10,
  	activePage: 1
  },
  inputValue: ''
};
const state = Rx.Observable.merge(
	pagination,
  ajax
).scan((state, changeFn) => changeFn(state), initialState);

// subscribe to state and update the dom on state changes
state.subscribe((state) => {
	const pagination = state.pagination;
  $('.pagination').html(render(pagination));
  $('#hello').html(pagination.activePage);
  console.log(pagination);
});

$(document).on('fakeajaxevent', (event, param) => {
	ajax.next(param);
}).trigger('fakeajaxevent', {
    pagination: {
      pages: 15
    }
  });

// To optimize our rendering we can check what state
// has actually changed
//let prevState = {};
//state.subscribe((state) => {
  //if (state.count !== prevState.count) {
    //$('#count').html(state.count);
  //}
  //if (state.inputValue !== prevState.inputValue) {
   ...