将类附加到 jQuery 对象

2023-12-01

我正在努力解决如何最好地结合 javascript 类和 jQuery 插件。这个问题不是很具体,我希望的是指向更多资源的指针。

基本上,我想将状态数据和私有方法存储在一个类中,然后扩展我调用插件的每个 jQuery 对象以拥有这些私有方法和属性。这样在插件内部我可以直接调用 jQuery 对象的方法。

I read 用于处理私有函数的 jQuery 插件设计模式(常见做法?),特别是大卫的回答,但是这每次都会初始化一个新的类,因此不能用于保存对象的状态。

我还发现http://fuelyourcoding.com/jquery-plugin-design-patterns-part-i/,建议创建一个类,然后将其存储在 .data() 中。

我认为理想情况下我想要得到的代码看起来像

(function( $ ){

  var methods = {
    init : function( options ) { // Initialize each object with a state and private methods },
    show : function( ) { 
      // testFoo() is a private method that checks the element's state
      if(this.testFoo()){
        // Relying on jQuery's html() method
        this.html() = this.fooTemplate();
      }
    }
  };

  // Boiler plate plugin from http://docs.jquery.com/Plugins/Authoring
  $.fn.myPlugin = function( method ) {
    // Method calling logic
    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.myPlugin' );
    }    
  };
})( jQuery );

最后,我似乎无法将私有方法直接烘焙到插件中,因为像“testFoo()”这样的方法将返回布尔值,因此不可链接。

想法?我以正确的方式处理这个问题吗?我应该使用另一种设计模式吗?也许根本不使用 jQuery 插件架构?


这是一个建议的解决方案。它结合了几种不同的方法(John Resig 的继承模型和 Alex Saxton 的插件继承模型)。

定义您的可继承插件:

(function ($) {

    My.Plugin = Class.extend({

        /*
        * Initialization (constructor)
        */
        init: function (element, meta) {
            var $meta = $.extend({ name: "pluginName" }, meta);

            // Call the base constructor
            this._super(element, $meta);

            // TODO: Add custom initialization code like the following:
            // this._testButton = $('.testButton', element).get(0);
        },


        /*
        * Public methods
        */

        show: function() {
             alert('This is a public method');

        },


        /*
        * Private methods
        */

        // DEMO: Overriding the base _paint method:
        _paint: function () {

            // "this._super()" is available in all overridden methods
            // and refers to the base method.
            this._super();

            alert('TODO: implement myPlugin._paint!');
        }


    });


    // Declare this class as a jQuery plugin
    $.plugin('my_plugin', My.Plugin);


})(jQuery);

定义基类

(function () {
    var initializing = false, fnTest = /xyz/.test(function () { xyz; }) ? /\b_super\b/ : /.*/;
    // The base Class implementation (does nothing)
    this.Class = function () { };

    // Create a new Class that inherits from this class
    Class.extend = function (prop) {
        var _super = this.prototype;

        // Instantiate a base class (but only create the instance,
        // don't run the init constructor)
        initializing = true;
        var prototype = new this();
        initializing = false;


        // Copy the properties over onto the new prototype
        for (var name in prop) {
            // Check if we're overwriting an existing function
            prototype[name] =
                   typeof prop[name] == "function"
                && typeof _super[name] == "function"
                && fnTest.test(prop[name])
                    ? (function (name, fn) {
                        return function () {
                            var tmp = this._super;

                            // Add a new ._super() method that is the same method
                            // but on the super-class
                            this._super = _super[name];

                            // The method only need to be bound temporarily, so we
                            // remove it when we're done executing
                            var ret = fn.apply(this, arguments);
                            this._super = tmp;

                            return ret;
                        };
                    })(name, prop[name])
                    : prop[name];
        }

        // The dummy class constructor
        function Class() {
            // All construction is actually done in the init method
            if (!initializing && this.init)
                this.init.apply(this, arguments);
        }

        // Populate our constructed prototype object
        Class.prototype = prototype;

        // Enforce the constructor to be what we expect
        Class.constructor = Class;

        // And make this class extendable
        Class.extend = arguments.callee;

        return Class;
    };
})();

插件创建

(function ($) {

    //  The "inheritance plugin" model
    //  [http://alexsexton.com/?p=51][1]

    $.plugin = function (name, object) {
        $.fn[name] = function (options) {
            var instance = $.data(this, name, new object(this, options));
            return instance;
        };
    };
})(jQuery);

从 javascript 调用您的插件:

$('#someElem').my_plugin({options: {}, data: {} /* you can modify your plugin code to accept anything */}).show();

Note:

这里的私有方法被标记为_methodName。这纯粹是惯例。如果你真的想隐藏它们,你可以使用模块模式(谷歌搜索或者这里是初学者的一个:http://www.adequatelygood.com/2010/3/JavaScript-Module-Pattern-In-Depth)

这是您要找的吗?

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

将类附加到 jQuery 对象 的相关文章

随机推荐

  • 在 PySimpleGUI 中渲染 HTML?

    有谁知道是否可以让 PySimpleGUI 渲染 HTML 我并不想要一个成熟的浏览器 只是一个位于 PySimpleGUI 窗口中的 HTML 查看器 我知道 tkinter 有一个名为tk html widgets 我也在调查什么web
  • 就地编辑 CMS 建议 [关闭]

    Closed 这个问题是无关 目前不接受答案 我需要找到一个 非常 易于使用 对于编辑 作者 的 CMS 最好使用类似的就地编辑SiteCore 不过 我们不需要像 SiteCore 这样庞大而强大的东西 用户需要能够添加页面 使用我们在开
  • SignalR 应用程序无法在 IIS 下运行

    我正在尝试在 Visual Studio 2012 中构建 SignalR 应用程序 我的问题是它在 Visual Studio 调试下运行良好 在 Windows 7 上使用 Visual Studio 2012 但是当我尝试在 Wind
  • 在QML插件的QGLWidget上渲染QImage

    我正在尝试写一个QML插件从视频中读取帧 使用自定义小部件来执行该任务 而不是 QtMultimedia Phonon 并且每个帧都转换为QImageRGB888 然后显示在QGLWidget 出于性能原因 现在屏幕上没有任何内容 并且屏幕
  • 比较盒装长整型值 127 和 128

    我想比较两个Long对象值使用if状况 当这些值是小于 128 the if条件工作正常 但当他们大于或等于128 比较失败 Example Long num1 127 Long num2 127 if num1 num2 Works ok
  • 运行时错误:populate() 在 Django 中不可重入

    我正在尝试部署django网站 项目名称是pom 我尝试使用 apache2 在 ec2 服务器中运行 django 网站并收到以下错误 阿帕奇错误文件 Fri Jul 24 12 37 33 621285 2015 info pid 20
  • 为什么多维数组中需要更高维度的维度范围?

    根据该帖子 将 2D 数组传递给 C 函数 int array 10 10 void passFunc int a 10 lt Notice 10 here passFunc array 从编译器内部的角度来看 为什么需要这个更高的维度 另
  • 奇怪地使用方括号来调用函数

    使用方括号调用函数是如何工作的 100 toString function toString native code 100 toString length 1 这里到底发生了什么 这是括号表示法 任何属性都可以使用点或方括号表示法来访问
  • 减小图像的文件大小

    我用安卓相机拍了一张照片 结果是一个字节数组 我通过将其写入SD卡 FileOutputStream 来保存它 结果是文件大小接近 3mb 的图像 我想减小此文件大小 因此压缩图像 如果在将字节数组写入输出流之前能够减少文件大小 那就太好了
  • 让你的程序使用 GUI

    我想编写一个程序 能够通过控制鼠标 键盘并能够 查看 屏幕上的内容来 使用 其他程序 I used AutoIt做类似的事情 但有时我不得不作弊 因为语言不是那么强大 或者也许只是我很糟糕 我无法用它做那么多 P 所以 我需要 截屏 然后我
  • IntelliJ:将 jar 包含在 jar 工件中

    使用 IntelliJ 9 0 2 Community Edition 在 Mac 上进行开发 我有一个程序依赖于两个库罐子 我已经弄清楚如何让 IntelliJ 为我的源代码制作一个 jar 使用 Artifact 选项卡 甚至将两个 j
  • 如何重写此查询以避免错误:您无法在 FROM 子句中指定用于更新的目标表

    update websites set master 2 where url select url from websites where id 12 显然 mysql 不允许您对正在更新的表运行选择查询 将其放入派生表中 这会具体化为临时
  • 接口没有构造函数,那么如何继承呢?

    据我所知 子类构造函数通过使用调用超类构造函数super 但既然接口没有构造函数 那么如何实现继承呢 但是由于接口没有任何构造函数 如何进行继承 很简单 接口不能有任何实例字段 因此无需构造任何内容 您无法将代码放置在接口中 至少在 Jav
  • Chrome 内容脚本未在 about:blank 页面中加载

    我正在开发一个 Chrome 扩展 它将根据以下清单加载内容脚本 content scripts matches
  • EWS 管理:获取预约的必需和可选与会者

    就我现在而言 我知道如何从交换服务器获取约会 但是一旦我想查看必填和可选的与会者 这些字段都是空的 我检查了约会三次 有一个与会者 除了我 我是否必须以不同的方式配置 Outlook 或者我是否遗漏了某些内容 List
  • python - 在 memmap 和 CPU 中工作时进行快速矩阵乘法和归约的方法

    您好 我在进行快速矩阵乘法 加法 function overwrite 和轴缩减求和以及在没有 RAM 的 CPU 上使用 numpy memmaps 时遇到问题 我认为 仅当使用 numexpr 时 我才有可能避免从点创建数组 For e
  • Go中如何获取本地IP地址?

    我想获取计算机的IP地址 我使用了下面的代码 但它返回127 0 0 1 我想获取IP地址 例如10 32 10 111 而不是环回地址 name err os Hostname if err nil fmt Printf Oops v n
  • 如何使用 Node 正确地从 mysql 返回结果?

    在代码中 var stuff i want stuff i want get info parm 以及函数 get info get info data var sql SELECT a from b where info data con
  • 如何在zxing中触发批量模式扫描

    我读到有一个可以在 zxing 中启用批量模式扫描的键 我可以知道如何在 Android 应用程序中启用此键吗 我目前正在使用这样的代码来单独扫描条形码 Intent intent new Intent com google zxing c
  • 将类附加到 jQuery 对象

    我正在努力解决如何最好地结合 javascript 类和 jQuery 插件 这个问题不是很具体 我希望的是指向更多资源的指针 基本上 我想将状态数据和私有方法存储在一个类中 然后扩展我调用插件的每个 jQuery 对象以拥有这些私有方法和