chitzui
chitzui

Reputation: 4098

Is it possible to use MobX without React?

I like MobX. I would like to use it in native JavaScript. I tried adding the CDN https://cdnjs.com/libraries/mobx Then I tried writing a class with MobX Syntax:

class MyStore {
  @observable data = 'foo'
}
const myStore = new MyStore();

but I get errors:

SyntaxError: illegal character

for the @ and:

ReferenceError: exports is not defined

from inside mobx.js file.

So it does not seem to be possible without React and without Blunding/Transpiler, is it? If not are there alternatives?

Thank you!

Upvotes: 5

Views: 3965

Answers (3)

Js-Craft Academy
Js-Craft Academy

Reputation: 29

No need for decorators. You can try the Mobx 4 approach:

import { decorate, observable} from "mobx"
class MyStore {
  data = 'foo'
}
decorate(City, {
    data: observable,
})
const myStore = new MyStore();

more details here https://medium.com/@mweststrate/mobx-4-better-simpler-faster-smaller-c1fbc08008da

Upvotes: 2

Joel Harkes
Joel Harkes

Reputation: 11661

As @someone235 said, it is possible.

to show you, here is an example without any react in it: https://jsfiddle.net/Lrt9pky4/

This is the code, although i can't enable decorators in SO so the below example doesn't work. the link does work.

const {observable, computed, autorun} = mobx;
class MyStore {
  @observable data = 'foo'
}
const myStore = new MyStore();      
autorun(()=> {
console.log(myStore.data);
document.getElementById('log').innerHTML += myStore.data + "<br />"
})

myStore.data = 'bar'
<script src="https://unpkg.com/mobx@3/lib/mobx.umd.js"></script>
<body>
  Log
  <hr/>
  <div id="log">
  </div>
</body>

You can use autorun and observe/intercept methods to receive notifications from changes, but you'd have to write all the other code yourself. (to react on these changes properly, phun intended).

Upvotes: 4

someone235
someone235

Reputation: 586

Yes, you can use MobX without React, but in your example you used decorators syntax, which belong to ES.Next, and is not natively supported by the browser, and requires a transpiler (Babel, for example).

If you want to use MobX directly in your browser without decorators, these instructions can be useful for you: https://mobx.js.org/best/decorators.html

Upvotes: 4

Related Questions