It is the first time I write a jQuery plugin without a tutorial. Now (September 28 2014), the jQuery site doesn't work (I don't know why), so I cannot find any resource there.
Below is part of my plugin that reports errors:
$(function($){
$.fn.dialog = function(command, options) {
var opts = $.extend( {}, $.fn.dialog.defaults, options );
//code
$.fn.dialog.handleCancel = function() {
};
$.fn.dialog.handleAccept = function() {
};
return this;
};
$.fn.dialog.defaults = {
// some other props
onCancel: $.fn.dialog.handleCancel(),
onAccept: $.fn.dialog.handleAccept()
};
// code
}(jQuery));
When I call the plugin ( $("#dialog1").dialog(/*..*/)
), the browser console, shows the following:
Uncaught TypeError: undefined is not a function
The error is on the line with onCancel: $.fn.dialog.handleCancel()
.
How can I access these methods, and where should them be? (I also want them to have access to $(this)
<- for the dialog itself)
Your handleCancel
and handleAccept
functions are not initialized until you call the $.fn.dialog
function. Therefore, they are undefined when you set the dialogs defaults.
Insert this code prior to $.fn.dialog.defaults
:
$.fn.dialog();
Try rearranging blocks within the piece , adding a filter , to prevent both handleCancel
and handleAccept
being called by default; eg,
(function($){ $.fn.dialog = function(command, options) { var $el = this; // access , pass arguments to methods $.fn.dialog.handleCancel = function(c) { $el.html(c + "led") }; $.fn.dialog.handleAccept = function(a) { $el.html(a + "ed") }; // call `handleCancel` or `handleAccept` , // based on `command` $.fn.dialog.defaults = { // some other props onCancel: command === "cancel" ? $.fn.dialog.handleCancel(command) : null, onAccept: command === "accept" ? $.fn.dialog.handleAccept(command) : null }; var opts = $.extend( {}, $.fn.dialog.defaults, options ); //code return this; }; // code }(jQuery)); $("button").on("click", function(e) { $("#result").dialog(e.target.id) })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button id="accept">accept</button><button id="cancel">cancel</button><br /> Result: <div id="result"></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.