jQuery 插件命名空间函数

jQuery Plugin Namespacing Functions(jQuery 插件命名空间函数)
本文介绍了jQuery 插件命名空间函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我正在创建一个范围相当大的 jQuery 插件.事实上,从技术上讲,该插件由几个共同工作的插件组成.

I'm creating a jQuery plugin that that is rather large in scope. In fact, the plugin technically consists of a few plugins that all work together.

(function($){
    $.fn.foo = function(){
        //plugin part A
    }
    $.fn.bar = function(){
        //plugin part B
    }
    $.fn.baz = function(){
        //plugin part C
    }
}(jQuery))

是否可以为 jQuery 插件命名,以便次要插件可以是较大插件的功能

Is it possible to namespace jQuery plugins such that the minor plugins could be functions of the larger plugin

$.fn.foo.bar = function(){}
$.fn.foo.baz = funciton(){}

这样可以避免污染 jQuery 函数命名空间.然后你可以调用插件像

This would keep from polluting the jQuery function namespace. You could then call the plugins like

$('#example').foo()
$('#other_example').foo.bar()

我自己尝试这个时遇到的问题是声明为 foo() 插件函数的属性的函数没有正确设置对this"的引用.'this' 最终指向父对象而不是 jQuery 对象.

The issue I have run into when trying this out myself is that the functions declared as properties of the foo() plugin function don't have their references to 'this' set properly. 'this' ends up referring to the parent object and not the jQuery object.

任何想法或意见将不胜感激.

Any ideas or opinions would be appreciated.

-马特

推荐答案

只要你使用 $.fn.foo.bar() -- this 指向$.fn.foo,这是您在 JavaScript 中所期望的(this 是调用函数的对象.)

As soon as you use $.fn.foo.bar() -- this points to $.fn.foo, which is what you would expect in JavaScript (this being the object that the function is called on.)

我注意到 jQuery UI 的插件(如可排序)中调用的函数如下:

I have noticed in plugins from jQuery UI (like sortable) where you call functions like:

$(...).sortable("serialize");
$(...).sortable({options});

如果你正在做这样的事情 - 你可以扩展 jQuery 本身:

If you were doing something like this - you could extend jQuery itself:

$.foo_plugin = {
  bar: function() {},
  baz: function() {}
}

$.fn.foo = function(opts) {
  if (opts == 'bar') return $.foo_plugin.bar.call(this);
  if (opts == 'baz') return $.foo_plugin.baz.call(this);
}

这篇关于jQuery 插件命名空间函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Google apps script get range of bytes from binary file(谷歌应用程序脚本从二进制文件中获取字节范围)
Sending Multiple attachments with Google Script from Google Drive(使用 Google 脚本从 Google Drive 发送多个附件)
Distributing Google Apps Scripts for Sheets in your company network(在您的公司网络中分发适用于表格的 Google Apps 脚本)
Upload file to my google drive from anyone using javascript(使用 javascript 将文件从任何人上传到我的谷歌驱动器)
quot;Shared Drivequot; support in Google Apps Script(“共享驱动器Google Apps 脚本中的支持)
Angular 2+ HTTP POST and GDrive API. Resumable file upload with name(Angular 2+ HTTP POST 和 GDrive API.带名称的可恢复文件上传)