@wix/velo-mvvm
v1.0.15
Published
Model-view-viewmodel for Velo
Downloads
50
Maintainers
Keywords
Readme
@wix/velo-mvvm
velo-mvvm
brings declarative reactive programming to Velo.
The idea is simple:
- Create an observable model
- Bind the view to the model
- Profit!
Installation
Follow the instructions here to install @wix/velo-mvvm
from npm on your Wix site.
Example
Counter:
import { createModel, bindView } from "@wix/velo-mvvm";
$w.onReady(() => {
const model = createModel({
count: 0,
});
bindView({
"#count": {
text: () => `${model.count}`,
},
"#inc": {
onClick: () => model.count++,
},
"#dec": {
onClick: () => model.count--,
},
});
});
Counter-list
import { createModel, bindRepeaters } from "@wix/velo-mvvm";
$w.onReady(() => {
const counters = createModel([
{ count: 0, _id: "0" },
{ count: 0, _id: "1" },
]);
bindRepeaters({
"#counterList": {
data: () => counters,
item: (dataItem, itemIndex) => ({
"#count": {
text: () => `${counters[itemIndex].count}`,
},
"#inc": {
onClick: () => counters[itemIndex].count++,
},
"#dec": {
onClick: () => counters[itemIndex].count--,
},
}),
},
});
});
API
createModel
mobx
's observable
function. You can read more about it in mobx
API docs here.
State can be a plain object, array, Map or Set
Bindings
type
An object in which each key is a velo-id and the value is an object with property-setter pair.
A setter must be a function.
bindView
Accepts elements Binding
.
An example:
Given the Text element with velo-id text1
, if we want to set its text
value, we can do it like this:
bindView({
"#text1": {
text: () => "This will be the text",
},
});
Note that the setter must be a Function. velo-mvvm
will run this function every time an observed piece of state changes.
bindRepeaters
Accepts an object with repeaters-velo-ids as keys and RepeaterBindings
as the value.
RepeaterBindings
Same as Bindings
but with an additional item
property.item
is a function that accepts a dataItem
and the itemIndex
and returns Bindings
. These bindings will apply to the specific item in the repeater.
Internally, velo-mvvm
uses the $item
function which is scoped to the repeater item. You can read more about that here.
Example:
Given a Repeater with id myRepeater
and an itemText
text element inside its item:
We can bind the itemText
like this:
bindRepeaters({
"#myRepeater": {
data: () => myObservableModel,
item: (dataItem) => ({
"#itemText": {
text: () => dataItem.description,
},
}),
},
});