2016-03-10 3 views
1

Я создал основной шаблон плагин на основе кода, сгенерированного здесь: http://starter.pixelgraphics.us/Вызов функции-члена внутри Jquery Plugin

Вот ссылка на очень основной скелет: https://jsbin.com/yatofefade/edit?html,js,console,output

$.curationPanel = function(el, options) { 
 
    
 
\t var base = this; 
 
\t base.$el = $(el); 
 
\t base.el = el; 
 
\t \t \t 
 
\t base.$el.data("curationPanel", base); 
 
\t \t \t 
 
\t base.init = function() { 
 
\t base.options = 
 
     $.extend({}, $.curationPanel.defaultOptions, options); 
 
\t }; 
 
\t \t \t 
 
\t base.runMe = function() { 
 
\t \t alert("I've Been Run"); 
 
\t }; 
 
\t \t \t 
 
\t base.init(); 
 
\t \t \t 
 
}; 
 
\t \t 
 
$.curationPanel.defaultOptions = { }; 
 
\t \t 
 
$.fn.curationPanel = function(options) { 
 
\t return this.each(function() { 
 
\t \t (new $.curationPanel(this, options)); 
 
\t }); 
 
}; 
 

 
$(".curationPanel").each(function(i, val) { 
 
\t var cp = $(this).curationPanel({}); 
 
\t cp.runMe(); 
 
});
<!DOCTYPE html> 
 
<html> 
 
<head> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
    <meta charset="utf-8"> 
 
    <meta name="viewport" content="width=device-width"> 
 
    <title>JS Bin</title> 
 
</head> 
 
<body> 
 
<div class="curationPanel">INSIDE THE PANEL<div class="curationErrors"></div></div> 
 
</body> 
 
</html>

Мой вопрос: почему я получаю сообщение об ошибке при попытке вызвать runMe() для созданного экземпляра curationPanel? Каков правильный способ создания вызываемых публичных функций внутри плагина?

+0

Вы должны разделить свой код здесь .. не только ссылка –

+0

Хорошо, обновлено ... thx. –

ответ

0

В вашем случае cp является объектом JQuery, а не экземпляр curationPanel, поскольку вы возвращаетесь this из метода плагина, поэтому ошибка.

Существует несколько способов сделать это.

Один из способов - разбить цепочку jQuery и вернуть экземпляр объекта плагина, как показано ниже. Помимо нарушения характера цепочки jQuery, другой недостаток этого дизайна заключается в том, что при любом вызове вы можете использовать это для инициализации плагина только для одного элемента, то есть если у вас есть селектор, который выбирает более 1 элемента, а затем вызывает плагин , плагин будет инициализирован только для первого элемента.

$.curationPanel = function(el, options) { 
 

 
    var base = this; 
 
    base.$el = $(el); 
 
    base.el = el; 
 

 
    base.$el.data("curationPanel", base); 
 

 
    base.init = function() { 
 
    base.options = $.extend({}, $.curationPanel.defaultOptions, options); 
 
    }; 
 

 
    base.runMe = function() { 
 
    snippet.log("I've Been Run"); 
 
    }; 
 

 
    base.init(); 
 

 
}; 
 

 
$.curationPanel.defaultOptions = {}; 
 

 
$.fn.curationPanel = function(options) { 
 
    return new $.curationPanel(this[0], options); 
 
}; 
 

 
$(".curationPanel").each(function(i, val) { 
 
    var cp = $(this).curationPanel({}); 
 
    cp.runMe(); 
 
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="curationPanel">INSIDE THE PANEL 
 
    <div class="curationErrors"></div> 
 
</div>


Другой способ получить плагин экземпляра с помощью API данных как

$.curationPanel = function(el, options) { 
 

 
    var base = this; 
 
    base.$el = $(el); 
 
    base.el = el; 
 

 
    base.$el.data("curationPanel", base); 
 

 
    base.init = function() { 
 
    base.options = $.extend({}, $.curationPanel.defaultOptions, options); 
 
    }; 
 

 
    base.runMe = function() { 
 
    snippet.log("I've Been Run"); 
 
    }; 
 

 
    base.init(); 
 

 
}; 
 

 
$.curationPanel.defaultOptions = {}; 
 

 
$.fn.curationPanel = function(options) { 
 
    return this.each(function() { 
 
    (new $.curationPanel(this, options)); 
 
    }); 
 
}; 
 
$(".curationPanel").each(function(i, val) { 
 
    var cp = $(this).curationPanel({}); 
 
    $(this).data('curationPanel').runMe(); 
 
});
<!-- Provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 --> 
 
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script> 
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="curationPanel">INSIDE THE PANEL 
 
    <div class="curationErrors"></div> 
 
</div>

+0

Является ли второй способ предпочтительным способом его выполнения, чтобы не нарушить цепочку jquery? –

+0

@DaveJohnshon да .... –

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