jQuery插件+ AMD =如何访问功能? [英] jQuery plugin + AMD = how to access functions?
问题描述
我正在将我的jQuery插件包装在AMD环境中.这是我的样板,
I am wrapping up my jQuery plugin in an AMD environment. This is my boilerplate,
!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不是函数
TypeError: $.fn.myPlugin.init is not a function
console.log($.fn.myPlugin.init());
console.log($.fn.myPlugin.init());
任何想法我做错了什么?以及如何访问myPlugin.prototype = {...}
内部的函数?
Any ideas what I have done incorrectly? And how can I access the function inside myPlugin.prototype = {...}
?
对此样板进行了测试,
tested with this boilerplate,
console.log($('.test li').plugin({
test: 'option1',
test2: 'option2'
}));
结果
Object[] // why is it empty?
还有
console.log($.fn.plugin.someMethod());
结果
TypeError:$ .fn.plugin.someMethod不是函数
TypeError: $.fn.plugin.someMethod is not a function
console.log($.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:实例为null//这是什么意思?它应该返回"hello world",不是吗?
TypeError: instance is null // what does it mean? It should return 'hello world', isn't it?
instance.someMethod("hello world");
instance.someMethod("hello world");
var plugin = $('.element').plugin();
var instance = $('.element').data('plugin',plugin);
console.log(instance); // returns - Object[]
console.log(instance.someMethod("hello world"));
结果
TypeError:instance.someMethod不是函数
TypeError: instance.someMethod is not a function
console.log(instance.someMethod("hello world"));
console.log(instance.someMethod("hello world"));
推荐答案
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
这篇关于jQuery插件+ AMD =如何访问功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!