具有多种功能的jQuery插件

Chr*_*ris 1 php jquery jquery-plugins

我目前有一个基于Web的应用程序,它严格依赖第三方soap服务器为站点提供信息.这个应用程序几乎没有javascript,从jQuery UI和一些jQuery的东西拉出一些元素(更多的简单比任何其他原因).

这个应用程序回归功能增强,我的想法是基于我们依赖的数据肥皂服务器,每个肥皂请求需要往返我们真的想减少在单个http请求上进行多次往返.因此,我的想法是使应用程序基于ajax并且仅更新用户希望看到的内容区域.

所以我们有这个基于php的服务器端库,它使用soap来获取信息,生成HTML并将数据发送给用户.现在开始有趣了,我们想要使用这个服务器端代码并​​使其模块化并构建一个jQuery插件以与服务器端进行交互.我收集的部分是如何在插件中有多个功能(也许这是错误的方法,请纠正我),我可以随意调用每个.

基本思路如下:

soap服务器允许访问其所有基础表,每个表都有一个特定的WSDL,并定义了一组可用于每个表的函数.所有表的这些功能都相同.

我们有例如:

  • 得到
  • getRecords
  • 插入
  • 更新
  • 删除

    (function( $ ){
    var methods = {
        init: function( options){
            //initialize the plugin 
            return this.each(function(){
                var $this = $(this),
                    data = $this.data();
            });
        },
        get : function(id){
            var getQuery = 'sys_id='+id;
            $.ajax({
                type: "POST",
                url: "get.php",
                data: getQuery,
                cache: false,
                success: function(result){
                    if(result.error){
                        //error notify user error occured... 
                    }else{
                        //success, update user ... 
                    }
                }
            });
            return false;
        },
        getRecords : function( ){
    
        },        
    };
    
    $.fn.myPlugin = function ( method ){
        if( methods[ method ]){
            return methods[ method ].apply(this, Array.prototype.slice.call( arguments,     1 ));
        }else if(typeof method === 'object' || !method){
            return methods.init.apply(this, arguments);
        }else{
            $.error('Method ' + method + 'does not exist on jQuery.ServiceNow');
        }
    };
    })( jQuery );
    
    Run Code Online (Sandbox Code Playgroud)

因此,对soap服务器的调用将需要ID来识别表中的哪个记录,getRecords调用接受查询并返回多个记录,插入插入记录,更新更新记录等.

要执行get调用,我想做一些事情,例如:

 $("#div").myPlugin.get(arguments); 
Run Code Online (Sandbox Code Playgroud)

结果是id ="div"的div将更新为myPlugin定义的与该元素相关的get函数的返回.

这是正确的方法,是否有更好的方法,我都湿了吗?这是我的第一个jQuery插件,我觉得我来自面向对象的世界,我习惯于构建东西,然后调用它们的函数/方法和/或使用字段.也许这就是我心态消失的问题.

感谢评论/反馈!

我的想法是在jQuery插件中构造类似的东西,以便能够将这些调用传递给服务器,服务器上的php将根据您想要的资源确定WSDL位置.

Dav*_*ang 5

这是一种简单而有效的方法,尽管使用您显示的代码,您可以这样调用.get:

$('#div').myPlugin('get', arguments);
Run Code Online (Sandbox Code Playgroud)

这是jQuery UI使用的方法.因此,您可能希望了解其Widget Factory的工作原理,或者甚至将其合并到您自己的代码中.


获得与您的示例类似的语法的另一种方法:

var methods = {/* Methods same as above */};

$.fn.myPlugin = function() {
    var Obj = function () {},
        obj;

    Obj.prototype = methods;
    obj = new Obj();
    obj.els = this;

    return obj;
};
Run Code Online (Sandbox Code Playgroud)

并称之为:

$('#div').myPlugin().get(arguments);
Run Code Online (Sandbox Code Playgroud)

如果您需要this在方法中引用以引用所选的jQuery对象(例如$('#div')),请this.els改用.