I’m trying to create a modular component structure that delegates object manipulation to each viewmodel. Instead of creating a huge viewmodel that handles everything the idea is that each viewmodel handles only one “level”.
This code does not work, but illustrates the way I was hoping it would work:
UPDATE: now the import works correctly, but the binding is not working
UPDATE: it works now!!
// person.js
import Component from 'can-component';
import DefineMap from 'can-define/map/';
import './person.less';
import view from './person.stache';
import Person from 'my-app/models/person';
import { ViewModel as AddressViewModel } from 'my-app/viewmodels/address/address';
export const ViewModel = DefineMap.extend({
newPerson: Person,
newAddressViewModel: AddressViewModel,
addNewInstance: function() {
// this should work initalizing the object
this.newPerson = {};
// this is what I would like to do:
this.newAddressViewModel = {};
// then invoke a method
this.newAddressViewModel.addNewInstance();
},
saveMe: function() {
this.newAddressViewModel.newAddress.saveAddress()
.then(addressData => {
this.newPerson.addressId = addressData._id;
this.newPerson.save();
});
}
});
export default Component.extend({
tag: 'my-app-person',
ViewModel,
view
});
// address.js
import Component from 'can-component';
import DefineMap from 'can-define/map/';
import './address.less';
import view from './address.stache';
import Address from 'my-app/models/address';
// import Address from 'my-app/models/address';
// import AddressViewModel from 'my-app/viewmodels/address/address';
export const ViewModel = DefineMap.extend({
newAddress: Address,
addNewInstance: function() {
this.newAddress = {};
},
saveAddress: function() {
return this.save();
}
});
export default Component.extend({
tag: 'my-app-address',
ViewModel,
view
});
// person.stache
<button ($click)="addNewInstance()"></button>
{{#newPerson}}
Name: <input {($value)}="name" /><br>
Last Name: <input {($value)}="lastName" /><br>
Address:<br>
<can-import from="my-app/viewmodels/address/" />
<my-app-address {(new-address)}="newAddressViewModel.newAddress" />
{{/newPerson}}
// address.stache
{{#newAddress}}
Street: <input {($value)}="street" /><br>
City: <input {($value)}="city" /><br>
{{/newAddress}}
This code should result in a form:
Name: […]
Last Name: […]
Address:
Street: […]
City: […]
Thanks!