开发者

jQuery - exposing events

开发者 https://www.devze.com 2023-01-26 03:13 出处:网络
I\'m trying to write my own jQuery plugin.My goal is to attach it to a form to override submission.I have the basics down, but my problem lies in \"exposing\" events.

I'm trying to write my own jQuery plugin. My goal is to attach it to a form to override submission. I have the basics down, but my problem lies in "exposing" events.

Here is what I want to do:

$('#myobject').myplugin({

    setting1: 'somevalue',
    beforesubmit: function(){ ... }

});

Here's what I have so far

$.fn.myplugin= function (options) {

    var settings = {
        setting1: '',
        beforesubmit: function() { return true; }
    };

    return this.each(function () {
        // If options exist, lets merge them
        // with our default settings
        if (options) {
            $.extend(settings, options);
        }

        //fire beforesubmit

        $(this).live("submit", function(){

            //do stuff
        }

    });

};

The ?? lies in how I fire the event off. I want to have other events t开发者_开发技巧oo, like onerror, aftersubmit, etc.


You can just call the method, replacing this:

//fire beforesubmit

With this:

if(settings.beforesubmit) settings.beforeSubmit();

You can also do this, adding whatever callback parameters you want, for example:

if(settings.beforesubmit) settings.beforeSubmit.call(this, someVariable);

An alternative (not appropriate for some situations) is to trigger your own events and let the jQuery binding model do the work, for example:

$(this).trigger("beforeSubmit");

Then elsewhere, bind to the event, for example:

$(".someElement").bind("beforeSubmit", function() { alert("submit!"); });
0

精彩评论

暂无评论...
验证码 换一张
取 消