繁体   English   中英

jQuery实用模板

[英]jQuery Utility Boilerplate

我正在尝试从jQuery Boilerplate创建一个jQuery插件。 我还想与此插件分开创建另一个实用程序类型的插件。 我一直在Google上下搜索各种方法来创建这样的方法。 我遇到了很多不同的类型,我不确定从哪里开始,所以我转向StackOverflow,希望可以帮助我。

我的目标是调用我的插件(实用程序方法/函数)并向其传递一些选项和数据,并根据所调用的函数将其返回给我一些数据,无论是对象,字符串还是数组。

我想做这样的事情:

<script>
  var options = {option1: 'value1', option2: 'value2'};
  var output = $.myplugin('methodName', options);
</script>

但是,我想尊重插件名称空间,适当的jQuery礼节等。

jQuery有两种类型的实用程序“插件”(由于缺乏更好的用语)。 第一种是向实际的jQuery对象添加方法,也是最容易实现的方法;第二种是向jQuery对象实例添加期望发生特定事件(链接,迭代,上下文管理,事件等)的实例。

实用功能

这很容易,因为您无需操纵jQuery对象,而只是像对任何普通JavaScript对象一样扩展jQuery。 只需将功能分配给jQuery(或简称$ )即可。

jQuery.myNewRadUtility = function myNewRadUtility(input, options) {
  // Do something with input and options
  return someValue; // return what you want
};

// Use it in your other code like so:
$.myNewRadUtility(input, options); // Or what ever you plan on doing

如您所见,它只是一个与其他函数一样的函数,只是将其分配给jQuery对象的属性。

为了使事情变得更通用/混合,您可以分离函数并像编写通用函数一样编写它,然后将其附加到jQuery特定文件中或实用地附加到jQuery。

function myNewRadUtility() {
  // Do one and only one amazing thing here.
}

// If we have jQuery then lets use it.
if (jQuery) {
  jQuery.myNewRadUtility = myNewRadUtility;
}

// Or if you need to massage the input / output to conform to jQuery then
if (jQuery) {
  jQuery.myNewRadUtility = function() {
    // Massage the input here
    var result = myNewRadUtility();
    // Massage the output here
    return result;
  };
}

jQuery插件

由于需要考虑如何使用jQuery对象,因此这有一些进步。 首先,像上面使用jQuery的fn属性一样,将其附加到原型。 然后,您必须管理实用程序需要使用的jQuery对象。 这意味着遍历它们。 最后,您需要根据创建的实用程序的目的返回相同或新的实例(通常不只是返回this )。

jQuery.fn.myNewRadUtility = function myNewRadUtility() {
  return $(this).each(function() {
    // Do something with $(this)
  });
};

// Use it in your other code like so:
$('p').myNewRadUtility();

显然,还有很多事情要做,还有很多事情可以做。 但这是品尝的最低要求。

您搜索这样的东西吗?

jQuery.myPlugin = function(method, args) {
    var myPlug = { 
         method1: function(y) {return y} 
         method2: function(a,b) {/*....*/}


    }; 
    return myPlug[method](arg)
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM