0

我创建了一个基于 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');

所以第二个实例采用第一个实例的值,我似乎无法让每个实例都使用他们自己的设置。

4

1 回答 1

0

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

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

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

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

于 2013-09-10T14:47:56.187 回答