我正在尝试构建一个Javascript类,该类需要一些选项并返回以构建表单。我希望Submit函数由传递给该类的选项确定。所有HTML都按预期输出,但是我不认为正在解析输出的javascript。当HTML呈现时,出现语法错误-“意外的标记函数”,而当我尝试提交表单时,出现参考错误-“未定义{functionName}。”
这是到目前为止的课程:
var ClassOptionsForm = function(options) {
this.options = options
this.getSubmissionFunction = function() {
switch (this.options.type) {
case 'standard':
return this.standardSubmit;
break;
case 'extendable':
return this.extendableSubmit;
break;
}
}
this.successHandler = "function (data, form) {\
$(form).find('.result').text('Success!').css('color', 'green');\
}"
this.failureHandler = "function (data, form) { \
$(form).find('.result').text('Something went wrong.').css('color', 'red');\
}"
this.submitFunctionName = this.options.optionName + "Submit";
this.standardSubmit = "function " + this.options.optionName + "Submit(form) {\
google.script.run\
.withSuccessHandler(" + this.successHandler + ")\
.withFailureHandler(" + this.failureHandler + ")\
.withUserObject(form)\
.setUserOption('" + this.options.optionName + "', form)\
}"
this.extendableSubmit = "function(this) {\
// Extendable Form Submit
}"
this.buildForm = function() {
var value = this.options.value;
return '\
<script type="text/javascript">\
' + this.getSubmissionFunction() + '\
</script>\
<h3>' + this.options.formTitle + '</h3>\
<form id="' + this.options.optionName + '" onsubmit="' + this.submitFunctionName + '(this)">\
' + Object.keys(value).reduce(function(list, key) {
return list + '<input name="' + key + '" value="' + value[key] + '"/>';
}, '') + '\
<button type="submit">Save</button>\
</form>\
'
}
}
这是在HTML文件中调用表单渲染函数的方式:
<?!= GoogleAnalytics().optionsForm.buildForm(); ?>
这是最终的HTML输出:
<script type="text/javascript">
function UAIDSubmit(form) {
google.script.run
.withSuccessHandler(function (data, form) {
$(form).find('.result').text('Success!').css('color', 'green');
})
.withFailureHandler(function (data, form) {
$(form).find('.result').text('Something went wrong.').css('color', 'red');
})
.withUserObject(form)
.setUserOption('UAID', form)
}
</script>
<h3>UAID</h3>
<form id="UAID" onsubmit="UAIDSubmit(this)">
<input name="id" value="********">
<button type="submit">Save</button>
</form>
我非常确定这与App Script清理HTML的方式有关,并且我知道有100万种方法可以不用动态JS来完成提交表单。我只是想让我的代码尽可能干燥,而且我很好奇。是否有任何其他解决方法都没有消除模板化JS?
答案 0 :(得分:0)
当您尝试提交表单时,它将无法正常工作,因为您可以将表单对象用作Google脚本函数中的参数,但是表单对象必须是该函数中的唯一参数。在这里阅读[1]
[1] https://developers.google.com/apps-script/guides/html/reference/run