依赖 jquery 在 Javascript 中实现模块模式
当模块代码依赖于第三方库(例如 jQuery)时,实现模块模式的最佳方法是什么?
var someModule = (function(){
//private attributes
var privateVar = 5;
//private methods
var privateMethod = function(){
return 'Private Test';
};
return {
//public attributes
publicVar: 10,
//public methods
publicMethod: function(){
return ' Followed By Public Test ';
},
//let's access the private members
getData: function(){
//make ajax call and do some processing and generate output
return privateMethod() + this.publicMethod() + privateVar;
}
}
})(); //the parens here cause the anonymous function to execute and return
someModule.getData();
我的问题是:我计划将所有代码放在一个库中,例如 JavaScript 文件中的时尚。
正如您在 getData()
方法中看到的,我计划进行 ajax 调用。我想为此使用 jQuery 库。现在我如何在依赖 jQuery 的同时编写 javascript 模块?
我应该让我的整个库成为 jQuery 插件吗?
What is the best way to implement module pattern, while the module code depends on third party libraries like jQuery for example?
var someModule = (function(){
//private attributes
var privateVar = 5;
//private methods
var privateMethod = function(){
return 'Private Test';
};
return {
//public attributes
publicVar: 10,
//public methods
publicMethod: function(){
return ' Followed By Public Test ';
},
//let's access the private members
getData: function(){
//make ajax call and do some processing and generate output
return privateMethod() + this.publicMethod() + privateVar;
}
}
})(); //the parens here cause the anonymous function to execute and return
someModule.getData();
My question is: I am planning to put all the code in a library like fashion in a javascript file.
As you see in the getData()
method, I plan to make ajax calls. I want to use jQuery library for this. Now how do I code a javascript module, while relying on jQuery ?
Should I make my whole library a jQuery plugin instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
可以找到一个很棒的教程/示例 此处或此处。我知道这不是模块模式,但它提供了与揭示模块模式相同的优点,并且允许您在需要时跨文件扩展命名空间。下面是该示例的代码。
A great tutorial/example can be found here or here. I know this isn't the module pattern, but it offers the same benefits of the revealing module pattern along with allowing you to extend the namespace across files if needed. Below is the code from that example.
您可以尝试这样的操作:
只需确保在执行此代码之前包含
jQuery.js
即可。You can try something like this:
Just make sure
jQuery.js
is included before this code is executed.