基于变量调用不同的函数

时间:2013-07-03 20:12:12

标签: jquery function variables simplify

真的,我正在查看代码中的模式,并意识到它可能会被简化。所以,这是最终目标。这是针对我正在编写的插件,它根据某些数据属性的存在调用不同的函数。

var a = $.extend({},$.bcplugins.defaults,options);
var b;

// a variable for each plugin's data attribute
var crumbsInstances = doc.find('[data-bcp-crumbs]'),
    copyrightInstances = doc.find('[data-bcp-copyright]'),
    activeNavInstances = doc.find('[data-bcp-activenav]');


// Determine wich functions get called
if (crumbsInstances.length) {
    crumbsInstances.each(function() {
        b = {};
        b = $$.extend({}, b, $(this).data(a.dataOptions));
        crumbs(a,b);
    });
}
if (copyrightInstances.length)  {
    copyrightInstances.each(function()  {
        b = {};
        b = $$.extend({}, b, $(this).data(a.dataOptions));
        copyright(a,b);
    });
}
if (activeNavInstances.length)  {
    activeNavInstances.each(function()  {
        b = {};
        b = $$.extend({}, b, $(this).data(a.dataOptions));
        activeNav(a,b);
    });
}

随着时间的推移,这个插件将会有越来越多的功能。我可以通过变量将其减少到一个if语句吗?

2 个答案:

答案 0 :(得分:1)

也许是这样的:

function processInstance($obj, callFunc){
  if ($obj.length)  {
    $obj.each(function()  {
        b = {};
        b = $$.extend({}, b, $(this).data(a.dataOptions));
        callFunc(a,b);
    });
  }
}

var crumbsInstances = doc.find('[data-bcp-crumbs]'),
    copyrightInstances = doc.find('[data-bcp-copyright]'),
    activeNavInstances = doc.find('[data-bcp-activenav]');

processInstance(crumbsInstances, crumbs);
processInstance(copyrightInstances, copyright);
processInstance(activeNavInstances, activeNav);

答案 1 :(得分:1)

要扩展上一个答案并添加到关于使其成为插件的评论中:

(function($) {
    if (!$.goData) {
        $.extend({
            goData: function() {
                function go($this, cb) {
                    var a = $.extend({},$.bcplugins.defaults,options);
                    if ($this.length) {
                        $this.each(function(i) {
                            b = {};
                            b = $.extend({}, b, $(this).data(a.dataOptions));
                            //  use of apply allows for element to be passed to function
                            cb.apply($this, [a, b]);
                        });
                    }
                }

                go($(document).find('[data-bcp-crumbs]'), $.goData.methods.crumbs);
                go($(document).find('[data-bcp-copyright]'), $.goData.methods.copyright);
                go($(document).find('[data-bcp-activenav]'), $.goData.methods.activeNav);
            }
        });
        $.goData.methods = {
            crumbs: function(a,b) { console.log(this, a, b); },
            copyright: function(a,b) { console.log(this, a, b); },
            activeNav: function(a,b) { console.log(this, a, b); }
        }
    }
})(jQuery);

// use
$.goData();

当然这需要先包含$.bcplugins.defaults,否则您只需将其添加到该插件即可。