如何扩展 jQuery 插件?
我想创建一个 jQuery 插件来包装图表组件。它将具有 addLineSerie 或 addBarsSerie 等功能。然后我想创建其他插件来扩展这个插件以添加新功能或覆盖所需的内容,但仍然能够调用原始插件功能。
我从下面的方法开始。它有点有效,但是,正如我后来意识到的那样,我无法调用原始的“父”实现(如果我创建 myB 的实例,我无法调用 myA.goA2)。
(function($){
$.fn.myA = function(settings) {
this.goA = function() {alert("goA: "+settings);};
this.goA2 = function() {alert("goA2: "+settings);};
return this;
};
})(jQuery);
(function($){
$.fn.myB = function(settings) {
this.myA(settings);
this.goA2 = function() {alert("goA2B: "+settings);};
this.goB = function() {alert("goB: "+settings);};
return this;
};
})(jQuery);
所以我有两个问题:
- 这种方法正确还是我应该以不同的方式这样做?
- 如何使“父级”和“子级”成为同一个实例并调用“父级”的实现?
谢谢。
I want to create a jQuery plugin to wrap a chart component. It will have functions like addLineSerie or addBarsSerie. Then I want to create other plugins that extend this one to add new functionality or overwrite what's needed but still be able to call the original plugin functions.
I started with the approach below. It kind of works but, as I realized later, I can't call the original "parent" implementation (if I create an instance of myB, I can't call myA.goA2).
(function($){
$.fn.myA = function(settings) {
this.goA = function() {alert("goA: "+settings);};
this.goA2 = function() {alert("goA2: "+settings);};
return this;
};
})(jQuery);
(function($){
$.fn.myB = function(settings) {
this.myA(settings);
this.goA2 = function() {alert("goA2B: "+settings);};
this.goB = function() {alert("goB: "+settings);};
return this;
};
})(jQuery);
So I have 2 questions:
- Is this approach right or I should be doing this in a different way?
- How do make the "parent" and the "child" be the same instance a yet get to call the "parent's" implementation?
Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这似乎是正确的,但要完成跨插件行为,您不能这样做:
编辑:修复对 myA 的调用并添加将进行的调用。查看工作小提琴:
http://jsfiddle.net/PqQgs/4/
This seems about right, but to accomplish cross-plugin behavior can't you just do this:
EDIT: fixed the call to myA and added the call that one would make. Check out the working fiddle:
http://jsfiddle.net/PqQgs/4/