Comments (9)
Hi @sunny-g,
in your example you pass the value of count to isObservable, which is just a boolean, which isn't false. For properties, pass the attribute name as string; isObservable(this, "count")
should return true.
from mobx.
@mweststrate oh duh, thanks for that clarification!
With that in mind, how would I set up an observer
function specifically for that property? this.count.observe
obviously won't work, and mobservable.observe(this...
is throwing an error (probably because the instance itself is not an observable).
The end goal is to tell the TodoStore to re-sort it's todos
array based on the count anytime a todo
's count has changed. I was doing it in my React render function, but thought that that was wasteful. Am I going about this functionality the wrong way?
from mobx.
You could do something along these lines:
let prevCount = x;
autorun(() => {
if (this.todos.length != prevCount) {
prevCount = this.todos.length;
// alter todo's
}
}
Besides that I can extend observe
to accept a second property parameter as well, so that it is possible to observe individual properties. That might be convenient in cases like these where you want access to the previous value
from mobx.
Ahh I think you may have slightly misunderstood my use case, though I like the approach you presented for other situations.
Say each of my todo
s has a click count and I want the ones with the most clicks to be at the top of the list. If I was displaying the count next to the todo
, mobservable would handle this perfectly (as it does in your getting started example).
However, I need to do some kind of sorting operation on some event (on each click or something else) to keep the list in order. Conventionally, I would emit an event to the store or call a function in the store on every click, telling it to sort itself.
One possible approach would be to do this within the todo
item's constructor (with the currently-non-existant second param property
as you suggested):
this.observe('count', () => {
this.store.sort();
})
but I'm sure there are approaches as well.
Going off the last example in your getting-started, I made these changes and got the minimum amount re-renders as expected:
ObservableTodoStore.prototype.sort = function() {
this.todos.sort(function(a, b) {
return a.count - b.count;
});
}
var todoStore = new ObservableTodoStore();
// and in the onToggleCompleted function:
onToggleCompleted: function() {
var todo = this.props.todo;
todo.completed = !todo.completed;
todo.count++
todoStore.sort();
},
I guess I'm mainly just curious as to what the best practices are for these kinds of data relationships and common patterns when using observables as opposed to events listeners or something else entirely. With listeners, you just emit the event and the action happens; with observables, if you have cascading changes, it becomes too easy to trigger too many observe
and autorun
functions.
from mobx.
Ah thanks for the extensive explanation of your use case. To me it seems that your sorting doesn't need to be a 'side effect' but can be derived purely from your data. So personally I would approach it roughly as follows:
/// in constructor
mobservable.extendObservable(this, {
sortedTodos: function() {
var sortedTodos = this.todos.slice();
sortedTodos.sort( /* the sort function */);
return sortedTodos;
}
});
This way you just keep the sorting a pure derivation of your state, and mobservable will figure out itself when the sorted list needs to be updated. Just make sure you perform all mutations on your original list and not on the sorted one ;-).
Note that sorted is performed one a clone, if you use lodash you could just write it as return lodash.sort(this.todos.slice(), sortFunction)
.
I hope this helps!
from mobx.
Thanks for the quick update! So then that would mean that I should pass todoStore.sortedTodos
as props to the TodoList
component, allowing us to store the todos as is and then just pass a cloned version of it to our components, correct?
from mobx.
Jup. Often I just pass complete stores around, so that their methods are
available in the components for modification.
On Mon, Nov 16, 2015 at 8:37 PM, Sunny Gonnabathula <
[email protected]> wrote:
Thanks for the quick update! So then that would mean that I should pass
todoStore.sortedTodos as props to the TodoList component, allowing us to
store the todos as is and then just pass a cloned version of it to our
components, correct?—
Reply to this email directly or view it on GitHub
#53 (comment)
.
from mobx.
Right on! Thanks so much for your help @mweststrate. This lib is pretty cool and the API you've exposed as well as the examples for using it so easily with React/React Native make it really powerful, though (for me at least) the simplicity is accompanied with an intellectual transition cost.
I'm going through the docs right now and will make a PR soon with some changes, but I'd also really like to blog about using mobservable with React with more intermediate to advanced architectural patterns, so expect to hear more questions from me soon if that's alright with you 😄
from mobx.
Thanks, PR's and blogs are really appreciated, so feel free to ask any further questions :)
from mobx.
Related Issues (20)
- @action @observable not work in @observer Class Component HOT 4
- Uncaught ReferenceError: process is not defined HOT 1
- mobx-react @inject does not work with new decorators HOT 1
- Using makeAutoObservable before variable initialization doesnt trigger state changes HOT 1
- @action field uses addInitializer from decorator context but that does not exist in the (new) spec HOT 2
- TS complains about @override
- `StubArray` workaround is incompatible with terser's `unsafe_arrows` option HOT 4
- mobx-react-lite component wrapped in `observer` renders twice in latest Next.js HOT 3
- Peer dependency issue for [email protected] HOT 4
- Migration from Mobx 4 > 6 HOT 6
- `trackDerivedFunction` pre-allocates memory for new deps array too aggressively HOT 1
- Invalid/extra warning in observable.box(array)
- Recommended pattern `MyComp = observer(function MyComp() {...})` leads to subtle bug
- Storing a Lit template in a mobx store does not work HOT 3
- Cannot update past `6.10.0` HOT 1
- Supporting of new Set methods in observable Sets HOT 3
- [feature] Investigate running MobX on top of signals standard / polyfill HOT 1
- [eslint-plugin-mobx] ESLint v9 Support
- `isolateGlobalState: true` can cause conflicts that prevent observable registration
- [mobx-react] `Maximum update depth exceeded` error since `mobx-react@8`
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from mobx.