繁体   English   中英

将ES6插件扩展为jQuery原型

[英]Extend ES6 plugin to jQuery prototype

我想请一些帮助,因为我无法使用模块和类转换ES6中的经典jQuery(v2)插件。

在ECMAScript 5中,我们可以将jQuery插件附加到jQuery原型中,如下所示:

app.js - 通过HTML <script>标签加载jQuery

$.fn.myPlugin = function() {};
$('div').myPlugin();

它的工作原理:)。 在ES6中,我会写这样的东西:

myPlugin.es6:

import $ from 'jquery';

export default class myPlugin extends $ {
 // Could i use constructor() method ???
}

app.es6:

import $ from 'jquery';
import myPlugin from 'myPlugin.es6';

$('div').myPlugin();

最后,它不起作用......
我搜索过,之前没有人问过这个问题。
我使用Babel将ES6转换为ES5。

$.fn只是一个对象。 $的原型中添加新属性没有任何魔力。 因此,代码$.fn.myPlugin = function() {}等于$.prototype.myPlugin = function() {}

$.fn === $.prototype; // true

为了能够调用一个函数$对象以标准方式( $('div').func()你需要这个功能添加到$对象。

你没有在你的es6代码中添加它。

从而,

import $ from 'jquery';

export default class myPlugin extends $ {
 // Could i use constructor() method ???
}

手段(差不多)

var myPlugin = function() {};

myPlugin.prototype = Object.create($.prototype);

return { default: myPlugin };

我不确定你应该扩展$ .fn,但也许你需要它。

import $ from 'jquery';
import myPlugin from 'myPlugin.es6';

它的意思是

var $ = require('jquery');
var myPlugin = require('myPlugin'); // a reference to the 'export.default' object from 'myPlugin.es6'

因此, $.fn对象和myPlugin函数之间没有任何关联。

你应该在某处创建连接。 它可以在一个特殊的模块中,比如plugins ,你可以将所有需要的插件注入$.fn对象:

import $ from 'jquery';
import plugin1 from 'plugin1.es6'; // should contain 'name'
import plugin2 from 'plugin2.es6';
...
import plugin10 from 'plugin10.es6';

[plugin1, plugin2, ..., plugin10].forEach(plugin => $.fn[plugin.name] = plugin);

或者你可以在'myPlugin.es6'中为导出的对象添加'initialize'方法,并在第一次使用之前调用它: init($) { $.fn.myPlugin = myPlugin; } init($) { $.fn.myPlugin = myPlugin; }

等等。

您可以像以往一样在ES6中的jQuery原型上安装新方法。 他们没有任何改变。 你不打算继承jQuery,所以使用classextends是没有意义的。

// myPlugin.es6:
import $ from 'jquery';

$.fn.myPlugin = function() {
    …
};

// app.es6:
import $ from 'jquery';
import 'myPlugin.es6';

$('div').myPlugin();

暂无
暂无

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

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