Tim*_*Dog 2 javascript architecture plugins
我正在寻找一个简单的javascript示例,演示javascript插件架构如何与大型javascript库(如raphael或jquery)一起工作.在任何一种情况下,您都可以通过确保自定义插件遵循以下模式来构建插件:jQuery.fn.pluginName- 假设我有一个库:
myLibrary = (function() {
//my fancy javascript code
return function() {
//my return object
};
});
Run Code Online (Sandbox Code Playgroud)
如何将fn上述myLibrary对象合并以确保他生成的插件可以调用?我实例化myLibrary如下:
var lib = new myLibrary();
Run Code Online (Sandbox Code Playgroud)
现在我在我的页面中添加了对插件的引用:
myLibrary.fn.simplePlugin = function() { //more fancy code }
Run Code Online (Sandbox Code Playgroud)
最后,我可以打电话给:
lib.simplePlugin();
Run Code Online (Sandbox Code Playgroud)
基本上,.fn在插件创建过程中使用时会发生什么魔法呢?
fnjQuery中的对象只是构造函数prototype属性的别名jQuery,这里有一个非常基本的结构:
(function() {
var myLibrary = function(arg) {
// ensure to use the `new` operator
if (!(this instanceof myLibrary))
return new myLibrary(arg);
// store an argument for this example
this.myArg = arg;
//..
};
// create `fn` alias and define some "core" methods
myLibrary.fn = myLibrary.prototype = {
init: function () {/*...*/}
//...
};
// expose the library
window.myLibrary = myLibrary;
})();
Run Code Online (Sandbox Code Playgroud)
然后,因为myLibrary是一个构造函数,你可以扩展它prototype(或fn在这个例子中是相同的对象):
// a "plugin"
myLibrary.fn.myPlugin = function () {
alert(this.myArg);
return this; // return `this` for chainability
};
myLibrary("foo").myPlugin(); // alerts "foo"
Run Code Online (Sandbox Code Playgroud)
我真的建议你阅读构造函数,这里有一些很好的资源:
| 归档时间: |
|
| 查看次数: |
1313 次 |
| 最近记录: |