I guess, because that’s easy and convenient
State management with use of viewmodel allows you to define helpers as mixins with separate (ViewModel.mixin) or shared (ViewModel.share) state. This way you do:
ViewModel.share({
myAwesomeSharedObject: {
myAwesomeHelper1: "cat",
myAwesomeHelper2: "dog"
}
});
and you can access every helper with any template you want by doing:
Template.MyAwesomeTemplate1.Viewmodel({
share: "myAwesomeSharedObject"
});
Template.MyAwesomeTemplate2.Viewmodel({
share: "myAwesomeSharedObject"
});
Now, whenever you set the state of any properties that are part of this Object:
Template.MyAwesomeTemplate2.Viewmodel({
share: "myAwesomeSharedObject",
onCreated: function() {
this.myAwesomeHelper2("fox"); //magically turn the dog into a fox!
};
});
both templates will see the value as “fox” instead of “dog”.
Other than that, you can directly call and update other helpers, easily refer to parents or children, load the template’s state from an object, refer to child component as a first level object in parent component and do many other things that help to manage the state.
It’s hella easy and convenient, like @avalanche1 said.
- Less code to get things done
- State is automatically saved for you across hot code pushes
- Save the state on the url
- Components can be used as controls
- Share state between components
- Compose view elements via mixins
- Inline/scoped styles
- Better error messages
That is one reason I am interested in Vue.js: it is more like object oriented and natural for holding variables (properties) in objects related to a template. I dod not experiemnt yet, so correct me folks if I am far in the ball field.
I would like feedback to know if what I am doing has unintended side effects but a good solution I found was creating “global” ReactiveVars. I created a folder imports/api/globals
and added an index.js
.
index.js
defines and exports my ReactiveVars:
const neededEverywhere = new ReactiveVar();
export { neededEverywhere };
Now in any Template, I can import { neededEverywhere } from '/imports/api/globals'
and call get and set. Reactivity works as expected from Session variables.
I created this package to save more time when structuring pages and optimizing performance for calling Meteor.subscribe