admin管理员组文章数量:1406924
I'm trying to create a jQuery plugin following some official best practices
(function($){
var methods = {
init : function( options ) {
this.options = options;
}
, add_that: function (elem) {
this.append(elem);
return (this);
}
, add_this: function (elem) {
return (methods.add_that(elem));
}
};
$.fn.test = function (method) {
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.test' );
}
};
})(jQuery);
I'd like the method add_that
to be able to append things to the matched element(s).
Now this method is called from add_this
.
$('#test').test('add_this', $('<div />'));
TypeError: this.append is not a function
Why can't I access to the plugin (this
) from add_that
?
I'm trying to create a jQuery plugin following some official best practices
(function($){
var methods = {
init : function( options ) {
this.options = options;
}
, add_that: function (elem) {
this.append(elem);
return (this);
}
, add_this: function (elem) {
return (methods.add_that(elem));
}
};
$.fn.test = function (method) {
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
} else if ( typeof method === 'object' || ! method ) {
return methods.init.apply( this, arguments );
} else {
$.error( 'Method ' + method + ' does not exist on jQuery.test' );
}
};
})(jQuery);
I'd like the method add_that
to be able to append things to the matched element(s).
Now this method is called from add_this
.
$('#test').test('add_this', $('<div />'));
TypeError: this.append is not a function
Why can't I access to the plugin (this
) from add_that
?
2 Answers
Reset to default 6Because the scope has changed when you've called it from add_this
. Notice that the original call used Function.apply
to scope the call to this
.
if ( methods[method] ) {
return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
So you can presumably get around the issue by using apply again in your method:
add_this: function (elem) {
return methods.add_that.apply(this,[elem]);
}
Live example: http://jsfiddle/XaUHV/
In the context you're using it "this" refers to methods.add_that
Since methods.add_that is a function there is no method on it called "append" by default.
本文标签: javascriptjQueryplugin methods callStack Overflow
版权声明:本文标题:javascript - jQuery - plugin methods call - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744361994a2602589.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论