jQuery插件+ AMD =如何访问函数?
我正在AMD环境中包装我的jQuery插件。 这是我的样板,
!function(root, factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else { factory(root.jQuery); } }(this, function($) { var defaults = { target: '' }; var myPlugin = function(options) { options = $.extend(true, {}, defaults, options); return options; }; myPlugin.prototype = { init: function(options) { return options; } }; $.fn.myPlugin = myPlugin; }); console.log($.fn.myPlugin.init());
错误,
TypeError:$ .fn.myPlugin.init不是函数
的console.log($ fn.myPlugin.init());
我做错了什么想法? 我怎样才能访问myPlugin.prototype = {...}
的函数?
编辑:
用这个样板测试,
console.log($('.test li').plugin({ test: 'option1', test2: 'option2' }));
结果,
Object[] // why is it empty?
和
console.log($.fn.plugin.someMethod());
结果,
TypeError:$ .fn.plugin.someMethod不是函数
的console.log($ fn.plugin.someMethod());
和,
// Plugin methods and shared properties Plugin.prototype = { // Reset constructor - http://goo.gl/EcWdiy constructor: Plugin, someMethod: function(options) { return options; } }; console.log($.fn.plugin.Plugin.prototype.someMethod("hello world"));
结果,
hello world
和,
var instance = $('.element').data('plugin'); instance.someMethod("hello world");
结果,
TypeError:instance为null //是什么意思? 它应该回归’你好世界’,不是吗?
instance.someMethod(“hello world”);
编辑2:
var plugin = $('.element').plugin(); var instance = $('.element').data('plugin',plugin); console.log(instance); // returns - Object[] console.log(instance.someMethod("hello world"));
结果,
TypeError:instance.someMethod不是函数
console.log(instance.someMethod(“hello world”));
你似乎并没有真正创建myPlugin的实例,而是试图静态访问这些方法,这可能是也可能不是你所追求的。
我发现每次使用插件时都要创建一个Plugin对象的实例。 一个例子:
!function(root, factory) { if (typeof define === 'function' && define.amd) { define(['jquery'], factory); } else { factory(root.jQuery); } }(this, function($) { 'use strict'; var defaults = { }; var Plugin = function(element, options) { this.element = element; this.options = options; }; Plugin.prototype = { constructor: Plugin, someMethod: function() { } } // Create the jQuery plugin $.fn.plugin = function(options) { options = $.extend(true, {}, defaults, options); return this.each(function() { var $this = $(this); $this.data('plugin', new Plugin($this, options)); }); }; // Expose defaults and Constructor $.fn.plugin.defaults = defaults; $.fn.plugin.Plugin = Plugin; });
从这里 – https://gist.github.com/simonsmith/4353587
现在你可以使用这样的插件:
require(['jquery', 'jquery.plugin'], function($) { $('.test li').plugin({ test: 'option1', test2: 'option2' }); });
对象的实例保存在数据属性中,因此始终可以访问它。 Herotabs使用这种技术:
var instance = $('.tabs').herotabs().data('herotabs'); instance.nextTab();
var plugin = $('.element').plugin(); var instance = $('.element').data('plugin'); console.log(instance); console.log(instance.someMethod("hello world"));
结果,
Object { element={...}, options={...}, constructor=function(), more...} hello world