diff --git a/sui/core/build.go b/sui/core/build.go index a837be93..0f2a23bb 100644 --- a/sui/core/build.go +++ b/sui/core/build.go @@ -705,7 +705,6 @@ func (page *Page) BuildScripts(ctx *BuildContext, option *BuildOption, component if !ispage { arguments = "component" } - injectScript := componentInitScript(arguments) // Get the Constants and Helpers var err error = nil @@ -730,14 +729,14 @@ func (page *Page) BuildScripts(ctx *BuildContext, option *BuildOption, component var imports []string = nil var source []byte = nil if page.Codes.TS.Code != "" { - code := fmt.Sprintf("%s\n%s", injectScript, page.Codes.TS.Code) + code := componentInitScript(arguments, page.Codes.TS.Code) source, imports, err = page.CompileTS([]byte(code), option.ScriptMinify) if err != nil { return nil, err } } else if page.Codes.JS.Code != "" { - code := fmt.Sprintf("%s\n%s", injectScript, page.Codes.JS.Code) + code := componentInitScript(arguments, page.Codes.JS.Code) source, imports, err = page.CompileJS([]byte(code), option.ScriptMinify) if err != nil { return nil, err diff --git a/sui/core/injections.go b/sui/core/injections.go index 3c9baaa1..d72d38af 100644 --- a/sui/core/injections.go +++ b/sui/core/injections.go @@ -132,9 +132,11 @@ const componentInitScriptTmpl = ` return r.Exec(name, data); }; + %s + if (this.root.getAttribute("initialized") != 'true') { - this.root.setAttribute("initialized", 'true'); - this.root.addEventListener("state:change", function (event) { + __self.root.setAttribute("initialized", 'true'); + __self.root.addEventListener("state:change", function (event) { const name = this.getAttribute("s:cn"); const target = event.detail.target; const key = event.detail.key; @@ -143,6 +145,7 @@ const componentInitScriptTmpl = ` const state = new __sui_state(component); state.Set(key, value, target) }); + __self.once && __self.once(); } ` @@ -181,8 +184,8 @@ func compEventInjectScript(eventID, eventName, component, dataKeys, jsonKeys, ha return fmt.Sprintf(compEventScriptTmpl, eventID, eventID, eventName, dataKeys, jsonKeys, component, component, handler) } -func componentInitScript(root string) string { - return fmt.Sprintf(componentInitScriptTmpl, root) +func componentInitScript(root string, source string) string { + return fmt.Sprintf(componentInitScriptTmpl, root, source) } // BackendScript inject the backend script