2015-04-09 7 views
0

Я создал простой плагин jQuery для изменения элемента в синий цвет и может передать ему параметр, чтобы изменить элемент на заданный цвет.Расширение плагина jQuery для изменения конфигурации

Теперь я хочу создать новый плагин, который изменяет цвет на желтый, не передавая цвет в качестве параметра. Я прочитал https://stackoverflow.com/a/4414356/1032531, но, похоже, он описывает добавление метода к объекту.

Как это лучше всего выполнить?

http://jsbin.com/xedohu/1/

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
     <title>Extend jQuery Plugin</title> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script> 
     <script type="text/javascript"> 
      (function($){ 
       var defaults = { 
        'color' : 'blue' 
       }; 

       var methods = { 
        init : function (options) { 
         var settings = $.extend({}, defaults, options); 
         return this.each(function() { 
          $(this).css('color',settings.color); 
         }); 
        }, 
        destroy : function() { 
         return this.each(function() {}); 
        } 
       }; 

       $.fn.changeColor = function(method) { 
        if (methods[method]) { 
         return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
        } else if (typeof method === 'object' || ! method) { 
         return methods.init.apply(this, arguments); 
        } else { 
         $.error('Method ' + method + ' does not exist on jQuery.changeColor'); 
        }  
       }; 
       }(jQuery) 
      ); 

      jQuery.fn.extend({ 
       changeColorToYellow: function() { 
        //What do I do? 
        //$.changeColor({color:'yellow'}) 
       } 
      }); 

      $(function() { 
       $('#myElement1').changeColor(); 
       $('#myElement2').changeColor({color:'red'}); 
       $('#myElement3').changeColorToYellow(); 
      }); 
     </script> 

    </head> 
    <body> 
     <p id='myElement1'>myElement1</p> 
     <p id='myElement2'>myElement2</p> 
     <p id='myElement3'>myElement3</p> 
    </body> 
</html> 
+1

Try: '$ (это) .changeColor ({цвет: 'желтый'});' – jcubic

+0

@jcubic Спасибо. Кажется, работает. Это считается правильным подходом? Для моего реального приложения мне нужно передать несколько параметров, и я просто пытаюсь сделать мой скрипт более кратким. См. Http://jsbin.com/folutu/1/ – user1032531

ответ

0

Вы можете использовать this.changeColor ({цвет: 'желтый'}) внутри changeColorToYellow. Не предлагая никаких вариантов, ваш плагин сделает все правильно. Это нормально, если вы не планируете создавать несколько плагинов, просто пытаясь сделать то же самое с разными цветами.

Код

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<html> 
    <head> 
     <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
     <title>Extend jQuery Plugin</title> 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.js" type="text/javascript"></script> 
     <script type="text/javascript"> 
      (function($){ 
       var defaults = { 
        'color' : 'blue' 
       }; 

       var methods = { 
        init : function (options) { 
         var settings = $.extend({}, defaults, options); 
         return this.each(function() { 
          $(this).css('color',settings.color); 
         }); 
        }, 
        destroy : function() { 
         return this.each(function() {}); 
        } 
       }; 

       $.fn.changeColor = function(method) { 
        if (methods[method]) { 
         return methods[method].apply(this, Array.prototype.slice.call(arguments, 1)); 
        } else if (typeof method === 'object' || ! method) { 
         return methods.init.apply(this, arguments); 
        } else { 
         $.error('Method ' + method + ' does not exist on jQuery.changeColor'); 
        }  
       }; 
       }(jQuery) 
      ); 

      jQuery.fn.extend({ 
       changeColorToYellow: function() { 
        this.changeColor({color: 'yellow'}); 
       } 
      }); 

      $(function() { 
       $('#myElement1').changeColor(); 
       $('#myElement2').changeColor({color:'red'}); 
       $('#myElement3').changeColorToYellow(); 
      }); 
     </script> 

    </head> 
    <body> 
     <p id='myElement1'>myElement1</p> 
     <p id='myElement2'>myElement2</p> 
     <p id='myElement3'>myElement3</p> 
    </body> 
</html> 
+0

Вместо того, чтобы создавать метод '$ .changeColorToYellow()', может ли он быть чем-то вроде $ .changeColor.ToYellow() '? – user1032531

+0

Это также возможно, если вы хотите назвать это так. Вы можете изменить changeColor, чтобы иметь несколько методов, таких как toYellow или toBlue. При этом просто инициализируйте его как {}, затем добавьте функции к объекту. –