第一次插件

时间:2013-02-01 04:35:25

标签: jquery jquery-plugins

大多数代码都有效,除了它没有抓住每个a

所需的每个.post
(function ($) {
'use strict';
var url = window.location.href.split('#')[0];
var post = $('.post').children('a[name]').attr('name');
var helpers = {
        "defaults": {
            "post": post,
            "href": url+'#',
            "send": 'true',
            "layout": 'button_count',
            "width": '125',
            "faces": 'false',
            "font": 'verdana',
            "action": 'like',
            "scheme": 'light',
        },
        "init": function (options) {

            var settings = $.extend({}, helpers.defaults, options),

                easyface = $('<div />').addClass('easyface fb-like').attr({
                    "data-href": settings.href + settings.post,
                    "data-send": settings.send,
                    "data-layout": settings.layout,
                    "data-width": settings.width,
                    "data-show-faces": settings.faces,
                    "data-font": settings.font,
                    "data-action": settings.action,
                    "data-colorscheme": settings.scheme
                });

            return this.each(function (i, elem) {
                var self = $(elem),                 
                    data = self.data('easyface');  
                if (!data) {   

                    self.data('easyface', easyface);
                    self.append(easyface);
                }
            });
        },
        "destroy": function () {
            return this.each(function (i, elem) {
                var self = $(this),                
                    data = self.data('easyface');   // test to see if we've already called init on this element

                $(window).unbind('.easyface');      // unbind any namespaced events, assuming you've namespaced them like "click.easyface"
                self.removeData('easyface');        // remove the data flag
                self.find('.easyface').remove();    // remove the appended div
            });
        }

    };
//define the method "easyface"
$.fn.easyface = function (method) {
    if (helpers[method]) {
        // call the method and pass in the settings
        return helpers[method].apply(this, Array.prototype.slice.call(arguments, 1));
    } else if (typeof method === 'object' || !method) {
        // default to the init method and pass in the arg
        return helpers.init.apply(this, arguments);
    } else {
        // throw an error
        $.error('Method ' + method + ' does not exist on jQuery.tooltip');
    }
};
}(jQuery));
 $(function() {
   $('body').append('<div id="fb-root"></div>');
   (function(d, s, id) {
     var js, fjs = d.getElementsByTagName(s)[0];
     if (d.getElementById(id)) return;
     js = d.createElement(s); js.id = id;
     js.src = "//connect.facebook.net/en_US/all.js#xfbml=1&appId=477049588983712";
     fjs.parentNode.insertBefore(js, fjs);
     }(document, 'script', 'facebook-jssdk'));
   });

2 个答案:

答案 0 :(得分:1)

检查语句的嵌套。您会发现您认为插件中的大部分代码实际上都不是。

$(this).attr(...)应该达到的陈述是什么?即使在插件内部移动后,它们也无法像当前所写的那样工作。他们需要(a)使用存储在options对象中的数据和(b)对创建的'<div class="fb-like"></div>'元素进行操作。

仔细查看语句$('.post-options').before().easyface();.before(),没有参数将无能为力,并且链接.easyface()(如果它没有错误地运行)可能也什么都不做。您可能想要$('.post-options').before(easyface(...));之类的内容,但要使其工作,您必须确保插件返回完全合成的<div class="fb-like"></div>元素而不是this

答案 1 :(得分:1)

关于你尝试过的一些指示,特别是你的模式:

$(this).attr('data-send', function () {
    return + send;
});
$(this).attr('data-layout', function () {
    return + layout;
});
$(this).attr('data-width', function () {
    return + width;
});

我最好用评论来解释:

// in your execution scope, "this" is the window object
$(this).attr('data-href', function () {
    // "href" is not in any scope of the IIFE
    // and is therefore either a global variable
    // or is undefined. Also the plus sign, when
    // used like this, will try to convert your
    // "href" to a number which is likely to return
    // NaN given that "href" is likely to be undefined
    // or a non-numeric string
    return + href;
});

那就是说,这就是我如何构建你的插件的评论,为什么我会这样构建它:

// Start with an IIFE and pass in either jQuery, or jQuery.noConflict
// which will map it to the dollar sign so that the the dollar sign
// cannot be overwritten by another library in the scope of its execution.
(function ($) {
    'use strict';
    // contain all methods and settings in a local variable.
    // this helps ensure clean namespacing and
    // preserves scope
    var helpers = {
            "defaults": {
                "post": "",                 //pass the post id in as a parameter
                "href": '/',
                "send": 'true',
                "layout": 'button_count',
                "width": '125',
                "faces": 'false',
                "font": 'verdana',
                "like": 'like'
            },
            "init": function (options) {
                // combine passed in options with the defaults in a new object
                var settings = $.extend({}, helpers.defaults, options),
                    // build the easyface element to attach
                    easyface = $('<div />').addClass('easyface fb-like').attr({
                        "data-href": settings.href + settings.post, // concatenate with your href here.
                        "data-send": settings.send,
                        "data-layout": settings.layout,
                        "data-width": settings.width,
                        "data-show-faces": settings.faces,
                        "data-font": settings.font,
                        "data-like": settings.like
                    });
                // return this.each to preserve chainability
                return this.each(function (i, elem) {
                    var self = $(elem),                 // cached reference to the element
                        data = self.data('easyface');   // test to see if we've already called init on this element
                    if (!data) {    // If the plugin hasn't been initialized yet
                        //Do more setup stuff here
                        self.data('easyface', easyface);
                        self.append(easyface);
                    }
                });
            },
            "destroy": function () {
                return this.each(function (i, elem) {
                    var self = $(this),                 // cached reference to the element
                        data = self.data('easyface');   // test to see if we've already called init on this element
                    // namespacing for the win
                    $(window).unbind('.easyface');      // unbind any namespaced events, assuming you've namespaced them like "click.easyface"
                    self.removeData('easyface');        // remove the data flag
                    self.find('.easyface').remove();    // remove the appended div
                });
            }
            /*
             * other example methods
             *
             *  "reposition": function () {},
             *  "show": function () {},
             *  "hide": function () {},
             *  "update": function (content) {}
             */
        };
    //define the method "easyface"
    $.fn.easyface = function (method) {
        if (helpers[method]) {
            // if the arg passed was a string that indicates a method above
            // call the method and pass in the settings
            return helpers[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            // if the arg passed was an object, or no arg was passed
            // default to the init method and pass in the arg
            return helpers.init.apply(this, arguments);
        } else {
            // don't know what to do with this
            // throw an error
            $.error('Method ' + method + ' does not exist on jQuery.tooltip');
        }
    };
}(jQuery));

在您的示例小提琴中,您可以将post id作为选项传递,如下所示:

$('.postfoot').easyface({
    "post": $('.post').children('a[name]').attr('name')
});

以下是一个更新的小提示: http://jsfiddle.net/zUeFL/9/