jquery插件的多个实例,新设置

时间:2013-09-10 14:34:48

标签: jquery jquery-plugins

我已经基于OO主体创建了一个新的jquery插件。该插件应该能够拥有多个实例,每个实例都有自己的设置/选项。但是,我现在实现它的方式,第一个设置是用于所有实例的设置。

我似乎无法找到解决方案:

我打开它:

// the semi-colon before the function invocation is a safety 
// net against concatenated scripts and/or other plugins 
// that are not closed properly
; (function ($, window, document, undefined) {

我执行以下功能:

    /**
    * Method for formatting a certain amount inside a provided element 
    * (the element can be an input or a regular span).
    *
    * @param object element         : Where the value will come from.
    * @param array options              : The different options to format     the amount. The options are culture, valuta and the amount of rounding.
    *
    * @return void;
    */
var AmountFormatter = function (element, options) {
    var elem = $(element);
    var self = this;

    //Defaults in case a value is missing
    var defaults = {
        culture: "",
        currency: "",
        rounding: 2
    };  

    // jQuery has an extend method that merges the 
    // contents of two or more objects, storing the 
    // result in the first object. The first object 
    // is generally empty because we don't want to alter 
    // the default options for future instances of the plugin
    var settings = $.extend({}, defaults, options || {});
    self._settings = settings;

    //Various functions

            //Start using the amountFormatter, this is a public function, so if you want to use the logic without a jquery selector, you can :).
    this.init = function (elements) {

        //If you the plugin is accessed with a jquery selector, format it as followed:
        if (elements instanceof jQuery) {
            //Check the value of each element and update it accordingly
            elements.each(function () {
                var $this = $(this);
                var elementIsInput = $this.is("input");

                value = $this.val() == "" ? $this.text().trim() : $this.val().trim();
                if(typeof value === 'undefined' || value === "") {
                    return ""; 
                }
                value = thousandSeperator(convertNumber(roundingOfNumber(value, self._settings.rounding)));

                //Checks whether we need to add the new amount as text or as a value
                return elementIsInput === true ?
                    elem.val(addCurrencyToNumber(value)) :
                    elem.text(addCurrencyToNumber(value));
            });
        }
        //Otherwise we:
        else {
            //First of, check if the provided variable is at least set and has at least one element
            if (elements != undefined || elements != null || elements.length !== 0) {
                if (elements instanceof Array) {
                    for (var i = 0; i < elements.length; ++i) {
                        var value = elements[i].toString();
                        elements[i] = addCurrencyToNumber(thousandSeperator(convertNumber(roundingOfNumber(value, self._settings.rounding))));
                    }
                    return elements;
                }
                else {
                    var value = elements.toString();
                    return addCurrencyToNumber(thousandSeperator(convertNumber(roundingOfNumber(value, self._settings.rounding))));
                }
            }
        }
    };


    this.init(elem);
};

在这里,我初始化了amountFormatter:

/*
* Initialize the amountFormatter
*/
$.fn.amountFormatter = function (options) {
    return this.each(function () {          
        var $this = $(this);            

        if ($this.data('amountFormatter')) return;

        var amountFormatter = new AmountFormatter($this, options);
        $this.data('amountFormatter', amountFormatter);
    });
};

然后我就把它关闭了:

})(jQuery, window, document);

我如何在我的页面上使用它:

第一个例子:

        // With options...
        container.amountFormatter({
            culture: "NL",                   
            currency:  "€",
            rounding: decimals
        });

        //Initiate the plugin and add the array to the list...
        var amountFormatterData = container.data('amountFormatter');

第二个例子:

// With options...
        container.amountFormatter({
            culture: "NL",                   
            currency:  " ",
            rounding: decimals
        });

//Initiate the plugin and add the array to the list...
        var amountFormatterData = container.data('amountFormatter');

所以第二个实例获取第一个实例的值,我似乎无法使它成为每个实例使用它们自己的设置。

1 个答案:

答案 0 :(得分:0)

我想我已经找到了。但如果我错了,请纠正我。

在我初始化amountFormatter的地方,我会检查存储为&#39; amountFormatter&#39;的数据。如果在第一次初始化amountformatter之后已经创建了它,它将获取该数据并返回:

if ($this.data('amountFormatter')) return;

删除上面的行,修复它。现在我总是创建一个新格式的格式化程序。我现在很可能会进一步更新,看看我是否可以提供让用户选择的选项。