I am writing a web application which uses YUI3 for all it's JS needs. I need functionality such as Tooltips, Tooltips whose content is determined by AJAX queries, Toggle Buttons and so on.
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 ?
return this;
This is unneccesary since function constructors return this
by default.
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.
There's a fundamental problem in your code:
var MyApp = function(){
this.toggleButton(node,config)
{
...
You're not defining a function for MyApp
. Instead, you try to invoke toggleButton each time you instantiate it. 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.
You can define MyApp
as a static Object:
var MyApp = {
toggleButton: function toggleButton() {
// your code
}
};
And you can use it anywhere by:
MyApp.toggleButton();
精彩评论