开发者

Loading data using different functions

I got a plugin which can load data using di开发者_Python百科fferent methods. I'm currently using a flag and a if to run the correct function. I'm trying to figure out how I can use a function pointer instead.

Here is a snippet:

$.fn.shureTable = function(options) {  
    var defaults = {  
        loadMethod: populateFromArray
    };  


    return this.each(function() {
        var $this = $(this);

        function loadJson(json) {
            if (json.appendMode == 0)
                        jQuery('tbody', $this).empty();

            options.loadMethod(json.Rows);
        }
        function populateFromArray(rowArray){
        }
    }
}

I get an error saying that populateFromArray is undefined. How can I control which function to use using options?


You're running in to issues due to scope. The function isn't available because it's inside the each statement.

But, you can so something like this and make a list of options, then pass which option you'd like to use. Likewise, you can make it so you can pass the custom function through.

<p id="red">Red colored</p>
<p id="green">Green colored</p>
<p id="blue">Blue colored</p>

<div>This is a custom function</div>

(function($){    
    $.fn.extend({
        color: function(method){
            // list of possible methods
            var methods = {
                red: function(a){ return '<span style="color:red;">'+a+'</span>' },
                green: function(a){ return '<span style="color:green;">'+a+'</span>' },
                blue: function(a){ return '<span style="color:blue;">'+a+'</span>' },
            }
            // assign the appropriate function based on the "method" argument
            var func = methods[method] || function(a){ return a; };

            // run through the elements and apply that function
            return this.each(function(i,e){
                $(e).html(func($(e).html()));
            });
        },
        color2: function(func){
            func = func || function(a){ return a; };
            return this.each(function(i,e){
                $(e).html(func($(e).html()));
            });
        }
    });
})(jQuery);

$('p').each(function(i,e){
    $(e).color($(e).attr('id'));
});

$('div').color2(function(a){
    return '<b style="color:#FF00FF">'+a+'</b>';
});

The color can be passed a name found in the methods object. color2 can be passed a whole function so you can extend what you'd like to do with it. (You could just check the parameters and change the behavior based on the type of argument, but this was for the sake of demo).

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜