2014-08-13 4 views
0

Я создаю один простой пользовательский плагин jQuery, используя jquery.boilerplate.js. Теперь я хочу, чтобы создать одну функцию, которая будет вызывать как,Как создать функцию для пользовательского плагина jQuery

var div1 = $("#div1").changeBackgroundColor({ 
    color: $('#colorCode').val().trim() 
}); 
div1.getColor(); 

Как определить, что getColor() метод JQuery плагин.

Пользовательские Plugin:

;(function($, window, document, undefined) { 
var pluginName = "changeBackgroundColor", defaults = { 
    color : "black" 
}; 

function Plugin(element, options) { 
    this.element = element; 
    this.settings = $.extend({}, defaults, options); 
    this._defaults = defaults; 
    this._name = pluginName; 
    this.init(); 
} 

$.extend(Plugin.prototype, { 
    init : function() { 
     console.log("Hello"); 
    } 
}); 

$.fn[pluginName] = function(options) { 
    this.each(function() { 
     if (!$.data(this, "plugin_" + pluginName)) { 
       $.data(this, "plugin_" + pluginName, new Plugin(this, 
        options)); 
      } 
     console.log(options); 
     if(options===undefined){ 
      $(this).css("background-color", defaults.color); 
     } else{ 
      $(this).css("background-color", options.color); 
     } 
    }); 
    return this; 
}; 

})(jQuery, window, document); 

Спасибо .... :)

ответ

1

Вы пропустили весь смысл плагинов и ООП.

  1. $.fn[pluginName] - должны играть роль инфраструктуры и делегировать фактическую работу к экземпляру Plugin.
  2. Plugin экземпляр должен выполнять фактическую работу с элементом.
  3. Если вы хотите вызвать методы на экземплярах Plugin, вы можете сделать $.fn[pluginName] для обработки особых случаев, когда options - это строка. $(selector).changeBackgroundColor('methodToBeCalled' /*rest arguments*/)

Demo.

;(function($, window, document, undefined) { 
var pluginName = "changeBackgroundColor", 
    defaults = { 
     color : "black" 
    }, 
    //methods to be called via $().changeBackgroundColor(name) 
    publicMethods = { 
     getColor: function() { 
      return this.settings.color;   
     }, 
     setColor: function(color) { 
      this.settings.color = color; 
      this.element.css('background-color', color);    
     } 
    }, 
    privateMethods = { //internal methods 
     init : function() { 
      console.log('init'); 
      this.setColor(this.getColor());    
     } 
}; 

function Plugin(element, options) { 
    this.element = $(element); 
    this.settings = $.extend({}, defaults, options); 

    this.init(); 
} 

//copy private and public methods 
$.extend(Plugin.prototype, privateMethods, publicMethods); 

$.fn[pluginName] = function(options) { 
    var out = [], 
     args = [].slice.call(arguments, 1); 
    this.each(function() { 
     var plugin = $.data(this, pluginName), 
      method; 

     if (!plugin) { //create new plugin 
      plugin = new Plugin(this, options)     
      return $.data(this, pluginName, plugin);    
     } 
     //handle method calls 
     if(typeof options === 'string' && publicMethods[options]) { 
      out.push(plugin[options].apply(plugin, args)); 
     }   
    }); 
    return out.length ? (out.length === 1 ? out[0] : out) : this; 
}; 

})(jQuery, window, document); 

Использование

$('#a').changeBackgroundColor(); 
$('#b').changeBackgroundColor({color: 'navy'}); 
$('#c').changeBackgroundColor({color: 'green'}); 
console.log($('#b').changeBackgroundColor('getColor')); 
console.log($('#b, #c').changeBackgroundColor('getColor')); 

$('#a').changeBackgroundColor('setColor', 'red'); 
console.log($('#a').changeBackgroundColor('getColor')); 
+0

@ Юрий. Вы должны написать блог на эту тему. Благодаря.....:) – Sheel

0

Определите метод как этот

$.fn.getColor = function() { 
    alert('getColor called'); 
} 

Basic Custom Plugin

+0

@bhushan ... но где я должен определить эту функцию ??? – Sheel

+0

Вы можете определить его в своем плагине custome или если вы собираетесь использовать его на своей странице html, тогда вы можете определить его на этой странице. –

+0

См. [Основной пользовательский плагин] (http://learn.jquery.com/plugins/basic-plugin-creation/) для справки. –

0

Создать свой плагин, как это:

$.fn.highlight = function(){ 
 
    this.css("background","yellow").css("color","black"); 
 
    return this; 
 
} 
 

 
$(".highlight").highlight().fadeIn();
В приведенном выше примере я создал простой JQuery плагин, который будет выделить element.I думаю вы должны это проверить http://mycodingtricks.com/jquery/how-to-create-your-own-jquery-plugin/

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