我想寻求一些帮助,因为我不能转换我的经典jQuery (v2)插件在ES6与模块和类。
在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。
发布于 2016-02-02 00:13:36
$.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‘中向导出的对象添加一个“初始化”方法,并在第一次使用之前调用它:init($) { $.fn.myPlugin = myPlugin; }
诸若此类。
发布于 2016-02-02 00:28:57
您可以像往常一样在jQuery原型的ES6中安装新的方法。对他们来说没有什么改变。您不会使用jQuery子类,所以使用class或extends是没有意义的。
// myPlugin.es6:
import $ from 'jquery';
$.fn.myPlugin = function() {
…
};
// app.es6:
import $ from 'jquery';
import 'myPlugin.es6';
$('div').myPlugin();https://stackoverflow.com/questions/35136874
复制相似问题