samedi 25 avril 2015

Accessing plugin methods in JavaScript callback function


I am building a user prompt plugin which uses jQueryUI dialog. Please see http://ift.tt/1JoS57z

The below script is only a very small excerpt of the total script, and is just used to demonstrate where I am having problems. When configuring the plugin, a callback function for validate is defined. This callback function needs to access functions in the main plugin (i.e. checkLength()), however, these functions appear to be in an unavailable in the namespace.

How can script in the callback access the plugin methods?

PS. I really don't like how I have assigned IDs to the JavaScript generated elements in order to validate them. Maybe a better way?

jQuery.fn.extend({
    dialog_prompt: function(settings) {

        function updateTips(t){}
        function checkLength( o, n, min, max ) {}
        function checkRegexp( o, regexp, n ) {}

        $('<div/>').appendTo('body').dialog({
            buttons: [
                {
                    text: "Ok",
                    click: function () {
                        var error=settings.validate();
                    }
                }
            ]
        })
    }
});

$(function(){
    $("#email").dialog_prompt({
        validate:function(){checkLength();}
    });

});


Aucun commentaire:

Enregistrer un commentaire