mobx-history
v2.0.1
Published
Mobx History
Downloads
89
Readme
mobx-history
Updated to 2.0.0 to use mobx v4 as peer dependency, enjoy it. Thanks to @kwoon and @ksandin Update to 2.0.1 to use history v4.9.0 @tregusti
Mobx wrapper of history, make it observable! mobx-history
object made three properties length
, location
, action
observable, so no more listener needed!
Installation
$ npm install --save mobx-history
or
$ yarn add mobx-history
Use CDN
- Include mobx first https://unpkg.com/mobx/lib/mobx.umd.js
- The include https://unpkg.com/mobx-history/umd/mobx-history.js
Then get the History
class:
// using ES6 modules
import History from 'mobx-history'
// using CommonJS modules
var History = require('mobx-history').History
// using CDN
var History = mobxHistory.History
Usage
Assuming you know how to use history
, if not, check its document.
Initalize mobx-history
with history
object:
import { createMemoryHistory } from 'history'
let history = new History(createMemoryHistory())
// or just change 'history' to 'mobx-history'
import { createMemoryHistory } from 'mobx-history'
var history = createMemoryHistory();
Then use mobx-history
object like original history
object, so few code changed in transitioning history
to mobx-history
. Original history
object can be visited in property history
.
mobx-history
object made three properties length
, location
, action
observable, so no more listener needed. It also provide a location setter to perform history.location = ...
as history.push(...)
. call stopListen
method to stop listening from original history
.
Props
getter
length- type:
number
- type:
The number of entries in the history stack.
getter
location- type:
object
- type:
The current location. history.location=...
would trigger history.push(...)
getter
action- type:
string
- type:
The current navigation action.
- history
- type:
object
- type:
Original history
object.
- ...props
Other properties would be same as in original history
object. See history document
Demo
Live example is in Codepen
const createMemoryHistory = mobxHistory.createMemoryHistory;
const {autorun} = mobx;
let h = createMemoryHistory();
autorun(()=>{console.log('pathname ' + h.location.pathname)});
autorun(()=>{console.log('action ' + h.action)});
autorun(()=>{console.log('length ' + h.length)});
autorun(()=>{console.log('search ' + h.location.search)});
// > pathname /
// > action POP
// > length 1
// > search
h.location = '/path';
// > pathname /path
// > action PUSH
// > length 2
h.push('/path2');
// > print '/path2'
// > length 3
h.replace('/path3');
// > pathname /path3
// > action REPLACE
h.replace({pathname:'/path3',search:'?q=1'});
// > search ?q=1