首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
社区首页 >问答首页 >我想使用javascript增加代码

我想使用javascript增加代码
EN

Stack Overflow用户
提问于 2017-10-21 06:52:49
回答 1查看 50关注 0票数 0

我有一个文件,其中有很多代码在一个函数中。假设函数名是MessageHandler,在该函数中,在条件为true之后,有很多条件和代码要执行。问题是,我希望使用javascript对代码进行模块化,这样就可以维护它,并且很容易找到bug。为每个logic.What创建不同的文件是最好的方法

“守则”的一部分:

代码语言:javascript
运行
AI代码解释
复制
if (userMessage == "/start" && event.channel == "ibc") {
        quickReplies.content.text = metaData.introduction.english;
        quickReplies.msgid = "afterIntro";
        quickReplies.options = metaData.language.english;

        context.sendResponse(JSON.stringify(quickReplies));//First introduction message is sent in english language.

    }

        else if (userMessage == "hi" || userMessage == "hello" || userMessage == "help" || userMessage == "hii" || userMessage == "hey" || userMessage == "wassup") {
        // add filipino and gujarati condition....
        if (context.simpledb.roomleveldata.preferredLang == "hindi") {
            quickReplies.content.text = metaData.introduction.hindi;
            quickReplies.options = metaData.language.hindi;
        } 

    else if(context.simpledb.roomleveldata.preferredLang=="gujarati"){

                quickReplies.content.text = metaData.introduction.gujarati;
            quickReplies.options = metaData.language.gujarati
        }
            else if(context.simpledb.roomleveldata.preferredLang=="filipino"){

                quickReplies.content.text = metaData.introduction.filipino;
            quickReplies.options = metaData.language.filipino;
        }


        else {
            quickReplies.content.text = metaData.introduction.english;
            quickReplies.options = metaData.language.english;
        }
        quickReplies.msgid = "afterIntro";

        context.sendResponse(JSON.stringify(quickReplies));


    } else if (event.messageobj.refmsgid == "afterIntro" || (userMessage.indexOf("change category") > -1) || (userMessage.indexOf("श्रेणी बदलें") > -1) ||(userMessage.indexOf("કેટેગરી બદ") > -1) ||(userMessage.indexOf("baguhin ang kategorya") > -1)) {
        if (userMessage == "अंग्रेजी" || userMessage == "english" || userMessage == "ઇંગલિશ" ||userMessage=="ingles")
        {
            context.simpledb.roomleveldata.preferredLang = "english";
            context.console.log("Enter into english section");
            // context.simpledb.roomleveldata.optinFlag = '1';
            userMessage = "english";
        } else if (userMessage == "हिंदी" || userMessage == "hindi" || userMessage == "હિન્દી") 
        {
            context.simpledb.roomleveldata.preferredLang = "hindi";
            // context.simpledb.roomleveldata.optinFlag = '1';
            userMessage = "hindi";
        } else if (userMessage == "गुजराती" || userMessage == "gujarati" || userMessage == "ગુજરાતી"){
            context.simpledb.roomleveldata.preferredLang = "gujarati";
            // context.simpledb.roomleveldata.optinFlag = '1'ફિલિપિનો"
            userMessage = "gujarati";
        } else if (userMessage == "filipino" || userMessage == "फिलिपिनो" || userMessage == "ફિલિપિનો") {
            context.simpledb.roomleveldata.preferredLang = "filipino";
            // context.simpledb.roomleveldata.optinFlag = '1'ફિલિપિનો"

            userMessage = "filipino";
        } else {
            userMessage = context.simpledb.roomleveldata.preferredLang
            // context.simpledb.roomleveldata.optinFlag = '1';
        }
        var languageArray = metaData.language.english;
        for (var i = 0; i < languageArray.length; i++) {
            if (userMessage == metaData.language.english[i]) {
                console.log("language"+metaData.language.english[i]);
                quickReplies.content.text = metaData.introMessage[metaData.language.english[i].toString()];
                quickReplies.msgid = "afterLanguage";
                quickReplies.options = metaData[metaData.language.english[i].toString()];
                context.sendResponse(JSON.stringify(quickReplies));///Intro message and categories to choose from.
            }
        }
    } else if (userMessage == 'change language' || (userMessage.indexOf('hindi') > -1) || (userMessage.indexOf('english') > -1) || (userMessage.indexOf('gujarati') > -1)|| (userMessage.indexOf('filipino') > -1)) {
        var currentLanguage = context.simpledb.roomleveldata.preferredLang;
        quickReplies.content.text = metaData.introduction[currentLanguage + 'language'];
        quickReplies.options = metaData.language[currentLanguage];
        quickReplies.msgid = "afterIntro";
        context.console.log("currentLanguage=======" + currentLanguage);
        context.sendResponse(JSON.stringify(quickReplies));////give option to change the language in preferred language with prefereed messsage describing what to do.
    } else if (userMessage == 'powered by gupshup') {
        context.sendResponse("This chatbot is powered by gupshup.io- world's leading filipinoform." +
            " Join the bot bandwagon along with- VentureBeat, Infosys, Sage, ICICI etc. " +
            "to build captivating and powerful experiences for your users.");
    } else if (event.messageobj.refmsgid == "afterLanguage")
    // }else if(context.simpledb.roomleveldata.optinFlag == '1')
    {
        context.simpledb.roomleveldata.optinFlag = '0';
        var quoteType;
        var items = [];
        var currentLanguage = context.simpledb.roomleveldata.preferredLang;
        for (var i = 0; i < metaData[currentLanguage].length; i++) //["Motivational", "Love", "Life", "Funny", "Positive"]
        {
            quoteType = metaData[currentLanguage][i].toLowerCase().toString(); //["Motivational", "Love", "Life", "Funny", "Positive"]
            context.console.log(userMessage + "--------quoteType----" + quoteType);
            if (userMessage == quoteType) {
                context.console.log("Cureeeeentttt quote typeeeee"+userMessage);
                catalogue.msgid = quoteType;
                // if(currentLanguage == "filipino")
                // {
                //  quoteType = metaData['english'][i+1].toLowerCase().toString(); //
                // }else
                // {
                    quoteType = metaData['english'][i].toLowerCase().toString(); // 
                // }

                    quoteType=quoteType.replace(/ /g,"_");
                    context.console.log("QQQQQQQQQQQQUOTEEEEEEE"+quoteType);
                var imageURL = context.simpledb.botleveldata[quoteType + 'JSONObj'];
                context.console.log("imageURL--------" + imageURL);
                if(JSON.stringify(imageURL).indexOf(currentLanguage)>-1)
                {
                    for (var j = 0; j < imageURL.length; j++) // {["ImageURL:'',Language:''"]}
                    {
                        context.console.log(imageURL[j]['Language'].toString() + "---------currentLanguage" + currentLanguage);
                            if (imageURL[j]['Language'].toString() == currentLanguage) {
                                context.console.log("imageURL[j]['Language'].toString()==============" + imageURL[j]['Language'].toString())
                                if (j % 9 == 0 && j != 0) {
                                    items.push({
                                        "title": "For More Quotes",
                                        "imgurl": "https://s3.amazonaws.com/gs-bot-images/Quote-Mister/search.jpg",
                                        "options": [{
                                            "type": "text",
                                            "title": "Keep Looking"
                                        }]
                                    });
                                    break;
                                } else {
                                    items.push({
                                        "title": metaData.carousal[currentLanguage + "_title"],
                                        "imgurl": imageURL[j]['Image URL'].toString(),
                                        "options": [{
                                            "type": "url",
                                            "title": "Preview",
                                            "url": imageURL[j]['Image URL'].toString()
                                        }, {
                                            "type": "url",
                                            "title": metaData.carousal[currentLanguage + '_button_text'][0],
                                            "url": "https://www.gupshup.io/developer/bot/devNewImageQuotes/share?text=" + imageURL[j]['Image URL'].toString(),
                                            "webview_height_ratio": "compact"
                                        }, {
                                            "type": "url",
                                            "title": metaData.carousal[currentLanguage + '_button_text'][1],
                                            "url": "https://www.facebook.com/sharer/sharer.php?u=" + imageURL[j]['Image URL'].toString(),
                                            "webview_height_ratio": "compact"
                                        }]
                                    });
                                    context.simpledb.roomleveldata['index'] = j;
                                }
                            }
                    }
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-10-21 07:12:32

您可以像使用模块一样使用模式。您的代码是否更清晰,就像历史一样,将每一段代码放在一个函数中,并将这些函数保存在有意义的文件中,当您需要帮助时,请按以下方式调用:

代码语言:javascript
运行
AI代码解释
复制
doActionOne()
doOtherAction(params)
isValidAction() // use is to validate true/false

这里有一个著名的设计图样簿。:)

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46864540

复制
相关文章
HAProxy配置示例和需要考虑的问题
本文目录: 1. 配置haproxy需要考虑的事情 2. 配置haproxy提供反向代理功能
星哥玩云
2022/07/13
1K0
HAProxy配置示例和需要考虑的问题
HashTable的使用示例
        // Create and initialize a new Hashtable.
Java架构师必看
2021/03/22
5660
simplifyEnrichment的使用示例
simplifyEnrichment主要针对富集分析的结果进行简化,并提供了一些强大的可视化函数。
医学和生信笔记
2023/08/30
7810
simplifyEnrichment的使用示例
Git示例教程 - 如何使用git rebase命令
现在我们想要将topic分支上的ABC提交重新rebase到最新的master分支上,可以执行如下命令:
KINGYT
2019/11/07
1K0
【EventBus】EventBus 使用示例 ( 最简单的 EventBus 示例 )
在 Module 下的 build.gradle 中导入 EventBus 依赖 ;
韩曙亮
2023/03/29
7240
【EventBus】EventBus 使用示例 ( 最简单的 EventBus 示例 )
InetAddress类的使用示例
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/152258.html原文链接:https://javaforall.cn
全栈程序员站长
2022/09/10
4380
如何确定您的企业需要使用在线CRM?
如果您是一个企业管理层,您可能已经听说过CRM,它的意思是客户关系管理。在线CRM是CRM系统的SAAS版本,无需安装任何软件,在网页上就可以将所有客户内容保存起来,简化您的工作方式,节省宝贵时间和金钱。但是您可能会想:“我为很么需要在线CRM,它对我有什么用?”很高兴你能有这个疑问,说明您开始思考在线CRM是否适合你,您可以通过以下方法确定您的企业是否需要CRM。
All in
2020/04/29
4050
OkHttp 使用示例
可以用来下载文件,打印header,打印body。string()方法对于小文档的响应来说是个既方便又高效的方法。但是如果一个文档太大(大于1M),就不要使用string()方法了,因为这个方法会把整个文档加载到内存中,在这种情况下可以把body当作流来处理。
代码拾遗
2018/07/24
2.8K0
mongojs使用示例
首先确保已经安装了nodejs与mongodb。 安装mongojs npm install mongojs 连接数据库 var databaseUrl="mydb"; // "username:password@example.com/mydb" var collections=["users","reports"]; var db=require("mongojs").connect(databaseUrl,collections); 查询操作 //find user  db.users.find(
用户2936342
2018/08/27
5340
使用 WDK 示例
Windows Driver Kit (WDK) 包含各种驱动程序的示例源代码。这些示例可在您编写自己的驱动程序时提供有用指导。在安装 WDK 时,示例将安装到 \src 目录的子目录中。
战神伽罗
2019/07/24
1.6K0
ThreadPoolExecutor 使用示例
我们上面讲解了 Executor框架以及 ThreadPoolExecutor 类,下面让我们实战一下,来通过写一个 ThreadPoolExecutor 的小 Demo 来回顾上面的内容。
崔笑颜
2020/06/08
6.2K1
currentStyle使用示例[通俗易懂]
Dom中的currentStyle属性.从字面上理解这是当前样式风格.没错currentStyle就是用来获取元素内Css的style样式属性值.比如说元素的width值height值.甚至元素的文本排放方式text-align,包括position等等.所有的css属性值都可以被获取.但是currentStyle仅支持IE浏览器,如若想在FF或基于Dom标准的其他浏览器内实现相同效果.请使用getComputedStyle属性.我在下面给出一个例子,来获取div的宽度值,文本如何排放.和绝对定位的值.已支持IE和FF其他浏览器.放心浏览!
全栈程序员站长
2022/09/14
4370
krpano使用示例
<hotspot name="spot1" style="skin_soundbutton" ath="13.267" atv="-6.054"   /> <hotspot name="spot2" style="skin_soundbutton" ath="-105.872" atv="-7.814"  /> <hotspot name="spot3" style="skin_soundbutton" ath="151.117" atv="-2.083"    />
JaneYork
2023/10/11
2890
QCustomPlot 使用示例
https://download.csdn.net/download/qq_40754866/18910871 运行环境:qt 5.14.2 win10 64位
全栈程序员站长
2022/11/03
5690
QCustomPlot 使用示例
Protostuff使用示例
User{firstName=’zhang’, lastName=’sanfeng’, email=’10000@qq.com’, friends=[User{firstName=’null’, lastName=’null’, email=’20000@qq .com’, friends=null, cars=null}], cars=[Car [color=null, car_name=宾利, price=null], Car [color=null, car_name=法拉利, price=null]]}
全栈程序员站长
2022/06/26
3710
ConcurrentHashMap使用示例
作者:mononite 链接:https://my.oschina.net/mononite/blog/144329(点击文末阅读原文前往) ConcurrentHashMap通常只被看做并发效率更高的Map,用来替换其他线程安全的Map容器,比如Hashtable和Collections.synchronizedMap。实际上,线程安全的容器,特别是Map,应用场景没有想象中的多,很多情况下一个业务会涉及容器的多个操作,即复合操作,并发执行时,线程安全的容器只能保证自身的数据不被破坏,但无法保证业务的行为
java达人
2018/01/31
2.6K0
Gearman使用示例
最近的一个旧项目重构过程中,使用到了gearman这个开源项目,简单来讲,这是一个类似MQ的异步系统,一边派发任务,一边处理任务(有类似MQ中的消息发送方与接收方),目前支持java,php等多种语言,缺点是存在单点问题(server的HA官方没有提供方案,需要二次开发)。
菩提树下的杨过
2018/09/20
8320
PHP-使用数组的示例
在这个示例中,$myArray3是一个多维数组,包含三个关联数组。每个关联数组都包含两个键值对,分别代表某个学生的数学和英语成绩。在输出多维数组的元素时,需要使用多个方括号来指定每个维度的索引值。
堕落飞鸟
2023/04/25
5010
点击加载更多

相似问题

C++模板类型检查编译时线程安全?

23

C++:如何创建动态模板类型

210

使用C++模板创建具有自定义组件的类

510

C++使用模板为基本类型创建别名?

10

查找模板类型c++的模板类型

10
添加站长 进交流群

领取专属 10元无门槛券

AI混元助手 在线答疑

扫码加入开发者社群
关注 腾讯云开发者公众号

洞察 腾讯核心技术

剖析业界实践案例

扫码关注腾讯云开发者公众号
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
查看详情【社区公告】 技术创作特训营有奖征文