First jQuery plugin, am I on the right track? [closed]
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this questionSo i assume this should be pretty simple... its just a custom Checkbox plugin that takes div's and turns them into checkboxes using css. All i really need it to do is basically swap css and trigger events. I only see need for these actions (init, check, uncheck, toggle, disable). Any way heres what i have so far, but im stuck on the toggle method and the last part in general...
(function ($) {
var method = {
init: function () {
$(this).addClass('cb-unchecked');
$(this).click(//Sh开发者_如何学运维ould call toggle method, but unsure syntax);
},
check: function () {
return this.each(function () {
$(this).removeClass('cb-disabled cb-unchecked').addClass('cb-checked').trigger('checked', this);
});
},
uncheck: function () {
return this.each(function () {
$(this).removeClass('cb-disabled cb-checked').addClass('cb-checked').trigger('unchecked', this);
});
},
toggle: function () {
return this.each(function () {
var t = $(this);
if (t.hasClass('cb-checked')) { //Should call the check function, but i dont know how... }
else if (t.hasClass('cb-unchecked')) { //Should call the uncheck function, but i dont know how...}
});
},
disable: function () {
return this.each(function () {
$(this).removeClass('cb-checked cb-unchecked').addClass('cb-disabled').trigger('disabled', this);
});
}
};
$.fn.customCheckbox = function (action) {
//Im slightly lost at what would go here
//if(method[action]){ method[action].apply(this, arguments); }//????
return this;
}
})(jQuery);
Am i headed in the right direction or should i be going about this completely differently?
Yes, you are on the right track. You wrapped it in (function($){..})(jQuery) to let jQuery play nicely with other javascript libraries. You maintain chainability by return this;
. You properly extend jQuery by using $.fn.customCheckbox = ...
. You can do as your comment says by applying the parameters to the function. Finally, just call it.
$("input[type='checkbox']").customCheckbox('init');
although i would probably move the init code into the body of $.fn.customCheckbox = function (action) {...}
when !action
$.fn.customCheckbox = function (action) {
if(!action){
// init here
}
// other logic here
return this;
}
The code in your comment is almost correct.
However, you need to remove the first argument (action
) before calling the method:
method[action].apply(this, Array.prototype.slice.call(arguments, 1));
You would call plugin methods the same way everyone else does:
this.customCheckbox("check");
Use this
$.fn.customCheckbox = function (action) {
if(action && method[action]){
var args = arguments;
args = $(args).slice(1);
method[action].apply(this, args);
}
return this;
}
精彩评论