【发布时间】:2013-12-05 09:07:01
【问题描述】:
我仍然无法理解这个 AMD jquery 插件。
// UMD dance - https://github.com/umdjs/umd
!function(root, factory) {
if (typeof define === 'function' && define.amd) {
define(['jquery'], factory);
} else {
factory(root.jQuery);
}
}(this, function($) {
'use strict';
// Default options
var defaults = {
};
// Constructor, initialise everything you need here
var Plugin = function(element, options) {
this.element = element;
this.options = options;
};
// Plugin methods and shared properties
Plugin.prototype = {
// Reset constructor - http://goo.gl/EcWdiy
constructor: Plugin,
someMethod: function(options) {
return options;
}
};
// Create the jQuery plugin
$.fn.plugin = function(options) {
// Do a deep copy of the options - http://goo.gl/gOSSrg
options = $.extend(true, {}, defaults, options);
return this.each(function() {
var $this = $(this);
// Create a new instance for each element in the matched jQuery set
// Also save the instance so it can be accessed later to use methods/properties etc
// e.g.
// var instance = $('.element').data('plugin');
// instance.someMethod();
$this.data('plugin', new Plugin($this, options));
});
};
// Expose defaults and Constructor (allowing overriding of prototype methods for example)
$.fn.plugin.defaults = defaults;
$.fn.plugin.Plugin = Plugin;
});
一些测试,
console.log($('.some-element').plugin({
test: 'option1',
test2: 'option2'
}));
我总是得到这个空对象,
Object[]
那么我该如何使用这个空对象呢?
我想访问插件里面的方法,
var plugin = $('.element').plugin();
var instance = $('.element').data('plugin',plugin);
console.log(instance); // an empty object again!
console.log(instance.someMethod("hello world"));
TypeError: instance.someMethod 不是函数
console.log(instance.someMethod("hello world"));
那么我该怎么做才能运行插件里面的方法呢?
它与传统的 jquery 插件有很大的不同。 AMD的太难理解了。知道如何让这个 AMD 像传统的一样工作吗!??
编辑:
终于有收获了,
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
为什么评论和回答的人很难指出这一点!叹息!
【问题讨论】:
-
正如我在您的另一个问题中指出的那样,您只是错误地使用了
.data()方法。使用var instance = $('.element').data('plugin'); -
是的,对不起,我很笨。我现在正在阅读
.data()的文档。谢谢。
标签: javascript jquery jquery-plugins requirejs js-amd