0
votes

How to initiate a creation of new instance of custom element when the bound object is updated? Let's say I have a visitDate in the view that can be changed by a user. When it's changed, I want to update the content of the page. View-model:

...
visitDateChanged() {
   this.shifts = [];
   this.newShift = {};
   this.newShift = {pstart: this.visitDate,  pstop: this.visitDate});
   this.service.getData(this.visitDate)
      .then(result => this.shifts = result);
    }
}

view:

<div repeat.for="shift of shifts | filterDate: visitDate">
    <shift-form shift.bind="shift" shifts.bind="shifts"></shift-form>
</div>
<div>
    <shift-form shift.bind="newShift" shifts.bind="shifts"></shift-form>
</div>

Note: shift-form is a custom element. Now if I change visitDate in the view, it calls visitDateChanged() and updates newShift and shifts variables. It detaches all shift-form instances called inside div repeat.for and attaches new instances according to objects inside shifts array. BUT it doesn't detach and reattach shift-form (doesn't create a new instance of shift-form) inside the second div. And I need a new instance of shift-form inside div when newShift is recreated. I managed to do it by changing newShift from an object to an array of one. Then

<div repeat.for="shift of newShift">
    <shift-form shift.bind="shift" shifts.bind="shifts"></shift-form>
</div>

does the trick but I don't think it's an elegant solution

1
What about creating a shiftChanged function to let you know when the shift property changes (when newShift is reset)? Would you mind explaining why you need to recreate the entire custom element? - Ashley Grant
Yes I can explain. The shift-form has a lot of variables set by the custom element's methods and they all need to be reset if I use shiftChanged. It's actually more code and I can forget to reset some variables by accident. - antarktikka
I'm not exactly sure what you're trying to do, but why don't you remove the second "newshift" form, and just push a new item (could be an empty object) onto the shifts array? Then the shift-form will be created / destroyed for you. - thinkOfaNumber

1 Answers

0
votes

As Ashley Grant suggested I have a reset function, but I am not listening for a change. I have a ref for the element and I call the reset function outside when needed.

<some-element controller.ref='someVariableNameHere'></some-element>

and in the controller that uses this ref:

this.someVariableNameHere.viewModel.reset();