2013-04-29 6 views
1

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

я кодирования:

(function($) { 

    var methods = { 

     init: function(){ 

      return this.bind('click',methods.slide()); 

     }, 

     slide: function() { 

      alert('I\'m sliding'); 

      // and lets the element color turns into green 
      return this.css('color','green');    

     } 

    }; 

    $.fn.myPlugin = 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 + ' doesn\'t exists in jQuery.myPlugin '); 

     } 

    } 

})(jQuery) 


$('#test').myPlugin(); 

<p id="test">Test</p> 

Я вижу предупреждение, но это только тогда, когда это init на старте, но как связать событие slide по щелчку?

+0

Я добавил комментарий к @ SpYk3HH ответа, до сих пор не может возражать, как использовать методы или Params снаружи. – Smash

ответ

6

Что сломано в вашего кода:

Насколько то, что нарушение в вашем коде, return $(this).on('click', methods.slide()); не нуждается в () после .slide. Вы буквально говорите ему, чтобы сделать этот звонок сразу, вместо того, чтобы назначать функцию. изменить его слишком return $(this).on('click', methods.slide);

ТАКЖЕ: return this.css('color','green'); должен быть return $(this).css('color','green');


Чтобы лучше объяснить JQuery плагинов:

Ниже мой самый основной из JQuery шаблона макета плагин. Из него вы можете проектировать практически любой плагин jQuery, который вы хотите, и иметь массу универсальности. Это довольно понятно. Просто просмотрите его, и если это поможет, здорово, если не сообщите мне, и я удалю его как ответ.

/* Example Plug-in Setup */ 
(function($) { 
    if (!$.myPlugin) { // your plugin namespace 
     $.extend({ 
      myPlugin : function(elm, command, args) { 
       return elm.each(function(index){ 
        /* THIS IS WHERE YOUR HEAVY WORK IS DONE AT */ 
        // do work to each element as its passed through 
        // be sure to use something like 
        //  return elm.each(function(e) { dor work }); 
        // as your final statement in order to maintain "chainability" 
       }); 
      } 
     }); 
     $.fn.extend({ 
      myPlugin : function(command) { 
       // nothing extra needed here. Simply plugin your namespace and account for any parameters you might need. remove the ones you dont. 
       return $.myPlugin ($(this), command, Array.prototype.slice.call(arguments, 1)); 
       // Params Explained: The first Param you "send" here is the jQuery Object of the "Element in Play". 
       //  This is the element(s) to which work will be applied. 
       // The Second is like any other jQuery Plugin (like stuff seen in jQueryUI), often it is a "command", thus I named it command, 
       //  Though, you might need it as an object, an array, or even undefined! You can make it whatever you want. Treat it 
       //  like any other parameter in any other "function/method" 
       // The last Param being passed here is simply an array of ALL other arguments/parameters sent to the function, again, change as you need too 
      } 
     }); 
     $.myPlugin.props = { // This could be used to store "properties" for your plugin, such as "variable timers", etc... 
      key1: "value", 
      key2: "value" 
     }; 
     $.myPlugin.methods = { // Here you might add more "functions/methods" needed to make you plugin work, such as loops, etc... 
      key1: function(param) { 

      }, 
      key2: function(param) { 

      } 
     }; 
     $.myPlugin.init = function(param) { // Here I designate a special spot for a special function, Initialize. 
       // You don't have to use this, or any of these extra spots, this is just simply a good practice in my opinion 
       // This keeps a centralized area in your code for what is going on to "start" your plugin 
      var key = "value", 
       key2 = { 
        subKey: "value" 
       }; 
       /* 
       /run any number of initializing functions here 
       /I prefer to make my param a value that can be a 
       / string with a possible object 
       / the string for holding a base configuration 
       / the object for any change in properties or base values for that config 
       */ 
     }; 
     $.myPlugin.defaults = { // Here is a section for possibly "overridable" options. 
       // Simple variables you "need" to make plugin work, but have a "default" 
       //  value that can be overriden by a later coder 
      key1: "value", 
      key2: { 
       prop1: { 
        subKey1: "value", 
        subKey2: "value" 
       }, 
       prop2: { 
        subKey1: "value" 
       } 
      }, 
      key3: function(param) { 

      } 
     }; 
    } 
})(jQuery); 

Просто используйте $.extend({ область, чтобы построить вам плагин, как если бы его там, где нормальная область JavaScript. fn.extend добавит знак стиля jquery вверх для $.myPlugin("element selector", command, args) & & $("element selector").myPlugin(command, args). Остальные - это просто переменные для разных вещей, которые могут потребоваться для хранения пространства имен, которое распространяется по всему плагину, поэтому вы не наступаете на носки.


Ответ на комментарий: Использование одного метода в другом так же просто, как с использованием метода. Я думаю, что вам не хватает, как плагин запускается. Вы пытаетесь использовать старый пример, и ваше событие не срабатывает, как вы ожидаете. Это по нескольким причинам, но одна из первых вещей, которые вам не хватает, это «ключ» к jQuery. Вам не хватает цепочки. Когда вы вызываете $.fn.extend, вы говорите jquery «Привет, у меня есть элемент obejct, я хочу, чтобы вы также добавляли свойства, а затем возвращаете мой объект!» Чтобы сделать это в «самых простых» форматах, давайте возьмем то, что у вас есть, и примените его к «куску» моего плагина и посмотрите, что происходит.

Прежде всего, давайте удостовериться, что у вас есть пространство имен для JUST YOUR PLUGIN. Таким образом, ни один другой плагин не может спорить с ним, если только он не загружен первым. Это ключевое правило для создания «экспансивных» javascript plguins.

(function($) { 
    if (!$.myPlugin) { // your plugin namespace 
     $.extend({ 
      myPlugin : function(elm, command, args) { 

Хорошо, с нашим пространством имен плагинов, мы можем добавить нашу «ожидаемую» работу.

  myPlugin : function(elm, command, args) { 
       // Here, I'm ensuring the return of the entire "element objecT" passed into this plugin, 
       //  in our case `$('#test')`, tho it could be several elements such as `$("input, select, textarea")` 
       return elm.each(function(index){ 
        // Here is where we apply work to EACH AND EVERY ELEMENT being sent in. 
        //  Keep in mind, prep work could be done before this, 
        //   for specific variables of data, however, only this 
        //   area affects the elements directly 

        // The following will "asign" the method `.slide` from our OWN methods to the "click" function of the element 
        $(this).on("click", function(e) $.myPlugin.methods.slide); 
       }); 
      } 
     }); 

Теперь мы добавим возможность сделать «традиционные» вызовы jQuery на нашем плагине. Такие вещи, как $.myPlugin("#test") ИЛИ $("#test").myPlugin()

 // this will simply add the ability to call our plugin via "traditional" jQuery Mark-up 
     $.fn.extend({ 
      myPlugin : function(command) { 
       return $.myPlugin ($(this), command, Array.prototype.slice.call(arguments, 1)); 
      } 
     }); 

Все, что осталось сделать, это создать этот метод слайд.Инициализация уже была установлена ​​с помощью вышеприведенной работы, хотя вы могли бы реструктурировать вызов return each на вызов «только», если «init» отправляется как параметр, хотя это приводит к большим проблемам «контроля».

 $.myPlugin.methods = { // Here you might add more "functions/methods" needed to make you plugin work, such as loops, etc... 
      slide: function(param) { 
       alert('I\'m sliding'); 
       // and lets the element color turns into green 
       return $(this).css('color','green');    
      } 
     }; 

Наконец, просто закройте все это!

} 
})(jQuery); 

See jsFiddle Here for full working example!

+0

слишком сложно для меня, извините – Smash

+1

серьезно? то вы можете просто работать с простым jQuery. Это самый простой плагин, который я мог бы подумать. Единственное, что здесь обширно, - это постоянное использование пространства имен. Это просто гарантирует, что ваш плагин играет хорошо с другими. – SpYk3HH

+0

Я добавлю еще несколько комментариев для вас, возможно, это поможет. Но это действительно очень просто. – SpYk3HH