简体   繁体   English

我的JavaScript体系结构(YUI3)有什么问题?

[英]Whats wrong with my JavaScript architecture (YUI3)?

I am writing a web application which uses YUI3 for all it's JS needs. 我正在编写一个Web应用程序,它使用YUI3满足所有JS需求。 I need functionality such as Tooltips, Tooltips whose content is determined by AJAX queries, Toggle Buttons and so on. 我需要诸如工具提示,其内容由AJAX查询确定的工具提示,切换按钮等功能。

I was not sure who to build an architecture to achieve all this. 我不确定谁能构建一个架构来实现所有这些目标。 I have taken the following approach 我采取了以下方法

var Myapp = function(){

    this.toggleButton(node,config)
    {
        YUI().use(....,function(Y){
            //code to convert NODE into a toggle button;

        });
    }
    return this;
};

In my application I then just convert all the buttons into toggle buttons by calling 然后,在我的应用程序中,我通过调用将所有按钮转换为切换按钮

var app = Myapp(); 
app.toggleButton(Y.all('.toggle-buttons'),{'text1':'TOGGLE_ME','text2':'TOGGLED_ME'});

All this works. 这一切都有效。 But I wanted to know from more experienced developers if there is anything fundamentally wrong with this approach. 但是我想从经验丰富的开发人员那里了解这种方法是否存在根本错误。

Is this a good way to use JavaScript ? 这是使用JavaScript的好方法吗?

return this;

This is unneccesary since function constructors return this by default. 这是不必要的,因为函数构造函数默认情况下返回this值。

var app = Myapp();

You forgot to call new Myapp() without the new keyword this will be the window object and you are effectively writing to global scope. 您忘记了不使用new关键字调用new Myapp()this将是window对象,并且您正在有效地写入全局范围。

There's a fundamental problem in your code: 您的代码中存在一个基本问题:

var MyApp = function(){

    this.toggleButton(node,config)
    {
     ...

You're not defining a function for MyApp . 您没有为MyApp定义函数。 Instead, you try to invoke toggleButton each time you instantiate it. 而是,您尝试在每次实例化它时调用toggleButton It should fail because the function is undefined 它应该失败,因为函数未定义


In your case, Class definition and instantiation is not needed because MyApp is being used as a utility. 在您的情况下,不需要将类定义和实例化,因为MyApp被用作实用程序。

You can define MyApp as a static Object: 您可以将MyApp定义为静态对象:

var MyApp = {
    toggleButton: function toggleButton() {
        // your code
    }
};

And you can use it anywhere by: 您可以通过以下方式在任何地方使用它:

MyApp.toggleButton();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM