代码之家  ›  专栏  ›  技术社区  ›  keparo

jqueryui如何知道如何绑定作为init选项提供的事件回调?

  •  1
  • keparo  · 技术社区  · 15 年前

    $.widget.bridge method (ln 71)

    我所说的一个例子是 autocomplete search event . 代码示例显示,我可以使用init选项绑定到“search”,但我没有看到任何特定于此行为的autocomplete代码。

    这种技术看起来很酷。我想利用它。

    2 回复  |  直到 15 年前
        1
  •  2
  •   user113716    15 年前

    我对jQueryUI代码不太熟悉,但下面是一个如何调用作为参数传递的回调的示例。

    试一试: http://jsfiddle.net/pshLK/

    当示例加载时,您将收到2个警报。这是为两个匹配的 <div>

    (function($) {
           // create myPlugin
        $.fn.myPlugin = function(options) {
               // iterate through all elements the selector matched
            return this.each(function() {
                    // Change the color to blue
                $(this).css('color','blue');
                    // Call the callback using the .call() method
                    //    so that we can pass the value of "this"
                    //    as the element in the iteration
                options.callback.call(this);
            });
        };
    })(jQuery);
    
       // Find all <div> elements on the page, and call myPlugin which
       //   receives an object as an argument that has a "callback" property
       //   whose value is the function that will be called in the plugin.
    $('div').myPlugin({
             // This function will run for each <div> displaying the ID of the <div>
        callback:function() { alert('the id is ' + this.id); }
    });
    
        2
  •  1
  •   cllpse    15 年前

    JavaScript中的函数可以作为值传递给其他函数并执行。例如。:

    function execute(fn)
    {
        fn(); // execute function passed as a parameter
    }
    
    var alertHelloWorld = function ()
    {
        alert("Hello World");
    };
    
    execute(alertHelloWorld); // this will alert "Hello World"
    

    因此jQuery Autocomplete插件所做的就是缓存传递给它的初始值设定项的任何函数,然后在需要时执行它们。即:当数据需要处理或数据已经处理时。

    下面是一个类似于Autocomplete插件的示例:

    // execute three functions contained in an object literal
    function execute(o)
    {
        o.One();
        o.Two();
        o.Three();
    };
    
    // call "execute" passing in object literal containing three anonymous functions
    // this will alert "One", then "Two", then "Three"
    execute(
    {
        One: function () { alert("One"); },
        Two: function () { alert("Two"); },
        Three: function () { alert("Three"); }
    });
    

    function execute(fn)
    {
        // execute function passed as a parameter with a parameter
        fn("Hello World");
    };
    
    execute(function (s)
    {
        // parameter "s" supplied by "execute" will contain "Hello World"
        alert(s);
    });