如何监听SurveyJS自定义问题类型中的内部变量变化?
问题
我定义了一个名为cascadedropdown的自定义问题类型,代码如下:
ComponentCollection.Instance.add({ // A unique name; must use lowercase name: 'casecadedropdown', // A display name used in the Toolbox title: 'casecade dropdown', // A default title for questions created with this question type defaultQuestionTitle: 'choose an option', elementsJSON: [{ type: 'dropdown', name: 'question1', title: 'question1', choices: levelOneArray, },{ type: 'dropdown', name: 'question2', title: 'question2', startWithNewLine: false, choices:[], },{ type: 'dropdown', name: 'question3', title: 'question3', startWithNewLine: false, choices:[], visible: {questionListLen} > 2 },{ type: 'dropdown', name: 'question4', title: 'question4', startWithNewLine: false, choices:[], visible: {questionListLen} > 3 } ], calculatedValues:[{ name:"questionListLen", expression: casecadeQuestionList.length } ], inheritBaseProps: true, }]
cascadedropdown加载完成后,casecadeQuestionList会被赋予新值,question3和question4的显示状态取决于casecadeQuestionList.length的值。我该如何监听casecadeQuestionList.length的变化?
我尝试了上述代码中定义calculatedValues的方式,但并未生效,请问应该如何解决?
解决方案
你的问题核心在于:calculatedValues无法直接引用外部变量,且外部变量变化时SurveyJS无法自动感知。可以按以下方式修复:
1. 给自定义问题添加可观测属性
在组件配置里声明casecadeQuestionList为SurveyJS可追踪的属性,让框架能感知它的变化:
ComponentCollection.Instance.add({ name: 'cascadedropdown', title: 'cascade dropdown', defaultQuestionTitle: 'choose an option', // 添加可观测属性 properties: [ { name: 'casecadeQuestionList', type: 'array', default: [] } ], elementsJSON: [ { type: 'dropdown', name: 'question1', title: 'question1', choices: levelOneArray, }, { type: 'dropdown', name: 'question2', title: 'question2', startWithNewLine: false, choices:[], }, { type: 'dropdown', name: 'question3', title: 'question3', startWithNewLine: false, choices:[], visible: "{casecadeQuestionList.length} > 2" }, { type: 'dropdown', name: 'question4', title: 'question4', startWithNewLine: false, choices:[], visible: "{casecadeQuestionList.length} > 3" } ], calculatedValues:[{ name:"questionListLen", expression: "{casecadeQuestionList.length}" }], inheritBaseProps: true, });
2. 正确更新属性值
更新casecadeQuestionList时,必须使用SurveyJS的setProperty方法,不能直接修改变量,否则无法触发变化监听:
// 假设自定义问题实例为question question.setProperty('casecadeQuestionList', newArrayValue);
备选:手动监听变化控制可见性
如果不想依赖计算值,也可以在组件初始化时手动监听属性变化,直接控制子问题显示:
ComponentCollection.Instance.add({ // 原有配置... onCreated: function(question) { // 监听casecadeQuestionList属性变化 question.onPropertyChanged.add((sender, options) => { if(options.name === 'casecadeQuestionList') { const listLen = sender.casecadeQuestionList.length; // 获取子问题并设置可见性 const question3 = sender.getQuestionByName('question3'); const question4 = sender.getQuestionByName('question4'); if(question3) question3.visible = listLen > 2; if(question4) question4.visible = listLen > 3; } }); }, // 其余配置... });
内容的提问来源于stack exchange,提问作者LibertyAndHappy
相关产品推荐
相关产品推荐

