Can replace() only be used once in a script?

Hello,

This is regarding: https://docs.squidex.io/02-documentation/developer-guides/scripting

This documentation mentions the replace() method a few times but doesn’t explicitly state that it can only be used once, yet when I tried to do something like:

var currentDateTime = new Date().toISOString().split('.')[0]+"Z";
ctx.data.FieldA.iv = currentDateTime;
replace();
ctx.data.FieldB.iv = currentDateTime;
replace();

Field B does not get replaced (specifically I have ‘Required when publishing’ set for both fields and this is a change script; validation states it cannot progress as only FieldB has not been set).

It’s easy enough to have a boolean variable that you set to true if replace() needs to be called at the end of the script so you only have one call to it, but just felt it wasn’t explicitly clear in the documentation if this is the case.

Short answer: “replace()” finishs the script and should be called once.

Long answer:
When you pass an object (e.g. the data) to a the script engine you have to bring it to a form that the script engine understands and the same, when you want to have get a value from the script engine.

To make it more efficient, the data script object maintains a list of changes and applies them to the data object when you call replace, therefore we do not have to construct a totally new data object and reduce memory allocations.

Due to async code it was also necessary in previous iterations of the script engine, to have an explicit “return”, therefore replace() finishs the scripts.

It could be solved in a better now, but I think it is okay as it is.

2 Likes

Thanks for the detailed response! I agree it’s absolutely fine as is, just wanted to confirm my understanding was correct and that I wasn’t missing anything.