jquery - 插件中不存在公共功能
问题描述
试图制作一个简单的 jquery 插件,但无法弄清楚我做错了什么。它的设计是制作一个多步骤的表格,效果很好。prevPage 和 nextPage 方法的逻辑基本相同,所以我将逻辑移动到 setPage() ,而不是从其他两个公共方法调用它。所有 3 种方法都应该是公开的,并且从插件外部可以正常工作。以下示例工作得很好,我可以将页面设置为该方法调用中的任何内容。但是我不能从 prevPage 或 nextPage 调用 setPage,它说该函数不存在。我想这是一个范围问题,但无法弄清楚我做错了什么。
例子:
$thing = $('#demo').book();
$('#myButton').on('click', function(){
$thing.setPage(2);
});
插入
(function($){
$.fn.book = function(options){
var defaults = {
onPageChange: function(){},
speed: 500
};
var settings = $.extend(defaults, options);
if (this.length > 1){
this.each(function(){ $(this).book(options) });
return this;
}
var pageIndex = 0;
var $this = $(this);
var pages = $this.children('section').css({width:'100%',height:'100%',position:'relative'});
this.initialize = function(){
pages.hide();
pages.first('section').show();
pages.find('.page-next').on('click', this.nextPage);
pages.find('.page-prev').on('click', this.prevPage);
return this;
}
this.getPageIndex = function(){
return pageIndex;
}
this.getPageCount = function(){
return pages.length;
}
this.setPage = function(index){
if (index >= 0 && index < pages.length && index != pageIndex){
oldPageIndex = pageIndex; // retain for callback info
$currentPage = pages.eq(pageIndex);
$newPage = pages.eq(index);
pageIndex = index;
pageName = ($newPage[0].hasAttribute("name")) ? $newPage.attr('name') : null; // used in callback
if (typeof settings.onPageChange == 'function'){
settings.onPageChange.call(this, oldPageIndex, pageIndex, pages.length, pageName );
}
if (index > pageIndex){ // move forward
$currentPage.hide("slide", {direction:"left"}, settings.speed, function(){
$newPage.show("slide", {direction:"right"}, settings.speed);
});
}else{ // move back
$currentPage.hide("slide", {direction:"right"}, settings.speed, function(){
$newPage.show("slide", {direction:"left"}, settings.speed);
});
}
}
return this;
};
this.nextPage = function(){
return $this.setPage(pageIndex+1);
};
this.prevPage = function(){
return this.setPage(pageIndex-1);
};
return this.initialize();
};
}(jQuery));
解决方案
我将 setPage 的逻辑放入一个名为 changePage() 的私有方法中,然后从公共方法中调用它。这似乎工作正常。无论如何,这可能是更好的设计实践。
推荐阅读
- java - 与集合和泛型相关的 Java 10 迁移问题
- python - 在大型 ZIP 文件中导入 Python 包
- c# - 从桌面客户端调用 Web API
- microsoft-teams - 如何在 ASP.NET 核心中验证从 Microsoft Teams 发送的消息有效负载?
- javascript - 使用 set-Attribute 设置 ng-pattern 不起作用
- html - 如何将html表单数据解析成文档
- angularjs - 如何解决 angularJs 可访问性中的断开链接?
- android - 可能未处理的 Promise Rejection (id:0) 错误:本机反应中的网络错误
- rest - RESTFul API 设计建议
- node.js - 将大文件上传到 Amazon S3 会在两分钟后创建两个副本