0

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

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 语句吗?

4

2 回答 2

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首先包含,或者您可以简单地将其添加到该插件中。

于 2013-07-03T20:46:36.857 回答
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);
于 2013-07-03T20:16:19.780 回答