2013-09-10 5 views
0

Я создал новый плагин jquery, основанный на принципалах 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'); 

Так второй экземпляр принимает значения первого экземпляра, и я не могу сделать так, чтобы каждый экземпляр использовал свои собственные настройки o они у них есть.

ответ

0

Я думаю, что нашел его уже. Но, пожалуйста, поправьте меня, если я ошибаюсь.

Где я инициализирую amountFormatter, я делаю проверку данных, хранящихся как «amountFormatter». Если он уже создан после того, как в первый раз amountformatter инициализирован, он принимает эти данные и делает возврат:

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

Так извлекая эти строки, установил ее. Теперь я всегда создаю новый экземпляр valueformatter. Теперь я, скорее всего, буду обновлять это дальше и посмотреть, могу ли я предоставить возможность разрешить пользователю выбирать.

+0

попробуйте использовать настройки, а не self._settings – massquote

Смежные вопросы