簡體   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