search
HomeWeb Front-endJS TutorialDetailed example of combining Bootstrap and KnockoutJs to achieve paging effect_javascript skills

KnockoutJS is an MVVM framework implemented in JavaScript. Very cool. For example, after the list data items are added or deleted, there is no need to refresh the entire control fragment or write JS to add or delete nodes by yourself. You only need to pre-define the template and attributes that conform to its syntax definition. Simply put, we only need to focus on data access.

1. Introduction

Since the company’s system needs to be revised recently, I plan to use KnockoutJs to make the web front-end for the new system. In the process of doing it, I encountered a problem - how to use KnockoutJs to complete the paging function. In the previous article, we did not introduce the use of KnockoutJs to implement paging, so in this article, we will supplement the use of KnockoutJs+Bootstrap to implement paging display of data.

2. Use KnockoutJs to implement paging

There are two ways to implement paging. The first is to load all the data, and then display all the data in pages; the second is to only load part of the data each time, and reload the following for each request. data.

For these two methods, paging implemented using the Razor method generally uses the second method to implement paging. However, for single-page programs, the first implementation method also has its benefits. It is completely suitable for not very large amounts of data. The first implementation method can be used, because in this case, the user experience of subsequent data loading will be very smooth. So these two implementation methods will be introduced here.

2.1 Implementation of loading partial data each time

The backend code here uses the code from the previous article, with just some additional sample data added. The specific backend implementation code is:

/// <summary>
 /// Web API 服务,为Web前端提供数据服务
 /// </summary>
 public class TaskController : ApiController
 {
  private readonly TaskRepository _taskRepository = TaskRepository.Current;
  public IEnumerable<Task> GetAll()
  {
   return _taskRepository.GetAll().OrderBy(a => a.Id);
  }
  [Route("api/task/GetByPaged")]
  public PagedModel GetAll([FromUri]int pageIndex)
  {
   const int pageSize = 3;
   int totalCount;
   var tasks = _taskRepository.GetAll(pageIndex, pageSize, out totalCount).OrderBy(a => a.Id);
   var pageData = new PagedModel()
   {
    PageIndex = pageIndex,
    PagedData = tasks.ToList(),
    TotalCount = totalCount,
    PageCount = (totalCount+ pageSize -1) / pageSize
   };
   //返回数据
   return pageData;
  }
 }
/// <summary>
 /// 任务仓储,封装了所有关于数据库的操作
 /// </summary>
 public class TaskRepository
 {
  #region Static Filed
  private static Lazy<TaskRepository> _taskRepository = new Lazy<TaskRepository>(() => new TaskRepository());
  public static TaskRepository Current
  {
   get { return _taskRepository.Value; }
  }
  #endregion
  #region Fields
  private readonly List<Task> _tasks = new List<Task>()
  {
   new Task
   {
    Id =1,
    Name = "创建一个SPA程序",
    Description = "SPA(single page web application),SPA的优势就是少量带宽,平滑体验",
    Owner = "Learning hard",
    FinishTime = DateTime.Parse(DateTime.Now.AddDays(1).ToString(CultureInfo.InvariantCulture))
   },
   new Task
   {
    Id =2,
    Name = "学习KnockoutJs",
    Description = "KnockoutJs是一个MVVM类库,支持双向绑定",
    Owner = "Tommy Li",
    FinishTime = DateTime.Parse(DateTime.Now.AddDays(2).ToString(CultureInfo.InvariantCulture))
   },
   new Task
   {
    Id =3,
    Name = "学习AngularJS",
    Description = "AngularJs是MVVM框架,集MVVM和MVC与一体。",
    Owner = "李志",
    FinishTime = DateTime.Parse(DateTime.Now.AddDays(3).ToString(CultureInfo.InvariantCulture))
   },
   new Task
   {
    Id =4,
    Name = "学习ASP.NET MVC网站",
    Description = "Glimpse是一款.NET下的性能测试工具,支持asp.net 、asp.net mvc, EF等等,优势在于,不需要修改原项目任何代码,且能输出代码执行各个环节的执行时间",
    Owner = "Tonny Li",
    FinishTime = DateTime.Parse(DateTime.Now.AddDays(4).ToString(CultureInfo.InvariantCulture))
   },
   new Task
   {
    Id =5,
    Name = "测试任务1",
    Description = "测试任务1",
    Owner = "李志",
    FinishTime = DateTime.Parse(DateTime.Now.AddDays(5).ToString(CultureInfo.InvariantCulture))
   },
   new Task
   {
    Id =6,
    Name = "测试任务2",
    Description = "测试任务2",
    Owner = "李志",
    FinishTime = DateTime.Parse(DateTime.Now.AddDays(6).ToString(CultureInfo.InvariantCulture))
   },
   new Task
   {
    Id =7,
    Name = "测试任务3",
    Description = "测试任务3",
    Owner = "李志",
    FinishTime = DateTime.Parse(DateTime.Now.AddDays(7).ToString(CultureInfo.InvariantCulture))
   },
  };
  #endregion
  #region Public Methods
  public IEnumerable<Task> GetAll()
  {
   return _tasks;
  }
  public IEnumerable<Task> GetAll(int pageNumber, int pageSize, out int totalCount)
  {
   var skip = (pageNumber - 1) * pageSize;
   var take = pageSize;
   totalCount = _tasks.Count;
   return _tasks.Skip(skip).Take(take);
  }
  public Task Get(int id)
  {
   return _tasks.Find(p => p.Id == id);
  }
  public Task Add(Task item)
  {
   if (item == null)
   {
    throw new ArgumentNullException("item");
   }
   item.Id = _tasks.Count + 1;
   _tasks.Add(item);
   return item;
  }
  public void Remove(int id)
  {
   _tasks.RemoveAll(p => p.Id == id);
  }
  public bool Update(Task item)
  {
   if (item == null)
   {
    throw new ArgumentNullException("item");
   }
   var taskItem = Get(item.Id);
   if (taskItem == null)
   {
    return false;
   }
   _tasks.Remove(taskItem);
   _tasks.Add(item);
   return true;
  }
  #endregion
 }

Web front-end implementation code:

@{
ViewBag.Title = "Index2";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="list2">
<h2 id="分页第二种实现方式-任务列表">分页第二种实现方式——任务列表</h2>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>编号</th>
<th>名称</th>
<th>描述</th>
<th>负责人</th>
<th>创建时间</th>
<th>完成时间</th>
<th>状态</th>
</tr>
</thead>
<tbody data-bind="foreach:pagedList">
<tr>
<td data-bind="text: id"></td>
<td><a data-bind="text: name"></a></td>
<td data-bind="text: description"></td>
<td data-bind="text: owner"></td>
<td data-bind="text: creationTime"></td>
<td data-bind="text: finishTime"></td>
<td data-bind="text: state"></td>
</tr>
</tbody>
<tbody data-bind="if: loadingState">
<tr>
<td colspan="8" class="text-center">
<img  src="/static/imghwm/default1.png"  data-src="/images/loading.gif"  class="lazy"     style="max-width:90%" / alt="Detailed example of combining Bootstrap and KnockoutJs to achieve paging effect_javascript skills" >
</td>
</tr>
</tbody>
<tfoot data-bind="ifnot:loadingState">
<tr>
<td colspan="8">
<div class="pull-right">
<div>总共有<span data-bind="text: totalCount"></span>条记录, 每页显示:<span data-bind="text: pageSize"></span>条</div>
<div>
<ul class="pagination">
<li data-bind="css: { disabled: pageIndex() === 1 }"><a href="#" data-bind="click: previous">&laquo;</a></li>
</ul>
<ul data-bind="foreach: allPages" class="pagination">
<li data-bind="css: { active: $data.pageNumber === ($root.pageIndex()) }"><a href="#" data-bind="text: $data.pageNumber, click: function() { $root.gotoPage($data.pageNumber); }"></a></li>
</ul>
<ul class="pagination"><li data-bind="css: { disabled: pageIndex() === pageCount }"><a href="#" data-bind="click: next">&raquo;</a></li></ul>
</div>
</div>
</td>
</tr>
</tfoot>
</table>
</div>
</div> 

The corresponding Js implementation is:

// 实现分页的第二种方式
var ListViewModel2 = function() {
//viewModel本身。用来防止直接使用this的时候作用域混乱
var self = this;
self.loadingState = ko.observable(true);
self.pageSize = ko.observable(3);
//数据
this.pagedList = ko.observableArray();
//要访问的页码
this.pageIndex = ko.observable(1);
//总页数
this.pageCount = ko.observable(1);
//页码数
this.allPages = ko.observableArray();
//当前页
this.currengePage = ko.observable(1);
self.totalCount = ko.observable(1);
this.refresh = function() {
//限制请求页码在该数据页码范围内
if (self.pageIndex() < 1)
self.pageIndex(1);
if (self.pageIndex() > self.pageCount()) {
self.pageIndex(self.pageCount());
}
//post异步加载数据
sendAjaxRequest("GET", function (data) {
// 加载新的数据前,先移除原先的数据
self.pagedList.removeAll();
self.allPages.removeAll();
self.totalCount(data.totalCount);
self.pageCount(data.pageCount);
self.loadingState(false);
for (var i = 1; i <= data.pageCount; i++) {
//装填页码
self.allPages.push({ pageNumber: i });
}
//for...in 语句用于对数组或者对象的属性进行循环操作。
//for ... in 循环中的代码每执行一次,就会对数组的元素或者对象的属性进行一次操作。
for (var i in data.pagedData) {
//装填数据
self.pagedList.push(data.pagedData[i]);
}
}, 'GetByPaged', { 'pageIndex': self.pageIndex() });
};
//请求第一页数据
this.first = function() {
self.pageIndex(1);
self.refresh();
};
//请求下一页数据
this.next = function() {
self.pageIndex(this.pageIndex() + 1);
self.refresh();
};
//请求先前一页数据
this.previous = function() {
self.pageIndex(this.pageIndex() - 1);
self.refresh();
};
//请求最后一页数据
this.last = function() {
self.pageIndex(this.pageCount() - 1);
self.refresh();
};
//跳转到某页
this.gotoPage = function (data, event) {
self.pageIndex(data);
self.refresh();
};
};
function sendAjaxRequest(httpMethod, callback, url, reqData) {
$.ajax("/api/task" + (url &#63; "/" + url : ""), {
type: httpMethod,
success: callback,
data: reqData
});
}
$(document).ready(function () {
var viewModel = new ListViewModel2();
viewModel.refresh();
if ($('#list2').length)
ko.applyBindings(viewModel, $('#list2').get(0));
}); 

Here is an introduction to the implementation idea of ​​using KnockoutJs to implement the paging function:

1. After the page is loaded, initiate an Ajax request to asynchronously call the REST service to request some data.

2. Then display the requested data through KnockoutJs binding.

3. Bind the corresponding paging information to Bootstrap paging

4. When the user clicks to turn the page, initiate an Ajax request to asynchronously call the Rest service to request data, and then display the requested data.

The above is the calling logic relationship of the code described above. You can refer to the corresponding JS code to understand the above description. At this point our second implementation method is completed.

2.2 Load all data for the first time, and then display all data in pages

Next, we introduce the first implementation method. With this implementation method, the user will only feel that the data is loading for the first time, and will not feel that the page is loading during the page turning process. In this way, for some When the data itself is not too much, the user experience is smoother.

The specific implementation idea is not to display all the requested data on the page, because there is too much data and the user may be dazzled if it is displayed on the page all at once. Displaying the data in pages will make it clearer for users.

The specific implementation code of Web front-end Js is:

var ListViewModel = function () {
var self = this;
window.viewModel = self;
self.list = ko.observableArray();
self.pageSize = ko.observable(3); 
self.pageIndex = ko.observable(0); //要访问的页码
self.totalCount = ko.observable(1); //总记录数
self.loadingState = ko.observable(true);
self.pagedList = ko.dependentObservable(function () {
var size = self.pageSize();
var start = self.pageIndex() * size;
return self.list.slice(start, start + size);
});
self.maxPageIndex = ko.dependentObservable(function () {
return Math.ceil(self.list().length / self.pageSize()) - 1;
});
self.previousPage = function () {
if (self.pageIndex() > 0) {
self.pageIndex(self.pageIndex() - 1);
}
};
self.nextPage = function () {
if (self.pageIndex() < self.maxPageIndex()) {
self.pageIndex(self.pageIndex() + 1);
}
};
self.allPages = ko.dependentObservable(function () {
var pages = [];
for (var i = 0; i <= self.maxPageIndex() ; i++) {
pages.push({ pageNumber: (i + 1) });
}
return pages;
});
self.moveToPage = function (index) {
self.pageIndex(index);
};
};
var listViewModel = new ListViewModel();
function bindViewModel() {
sendAjaxRequest("GET", function (data) {
listViewModel.loadingState(false);
listViewModel.list(data);
listViewModel.totalCount(data.length);
if ($('#list').length)
ko.applyBindings(listViewModel, $('#list').get(0));
}, null, null);
}
$(document).ready(function () {
bindViewModel();
}); 

The implementation of its front-end page is similar to the previous implementation. The specific page code is as follows:

@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<div id="list">
<h2 id="任务列表">任务列表</h2>
<div class="table-responsive">
<table class="table table-striped">
<thead>
<tr>
<th>编号</th>
<th>名称</th>
<th>描述</th>
<th>负责人</th>
<th>创建时间</th>
<th>完成时间</th>
<th>状态</th>
</tr>
</thead>
<tbody data-bind="foreach:pagedList">
<tr>
<td data-bind="text: id"></td>
<td><a data-bind="text: name"></a></td>
<td data-bind="text: description"></td>
<td data-bind="text: owner"></td>
<td data-bind="text: creationTime"></td>
<td data-bind="text: finishTime"></td>
<td data-bind="text: state"></td>
</tr>
</tbody>
<tbody data-bind="if:loadingState">
<tr>
<td colspan="8" class="text-center">
<img  src="/static/imghwm/default1.png"  data-src="/images/loading.gif"  class="lazy"     style="max-width:90%" / alt="Detailed example of combining Bootstrap and KnockoutJs to achieve paging effect_javascript skills" >
</td>
</tr>
</tbody>
<tfoot data-bind="ifnot:loadingState">
<tr>
<td colspan="8">
<div class="pull-right">
<div>总共有<span data-bind="text: totalCount"></span>条记录, 每页显示:<span data-bind="text: pageSize"></span>条</div>
<div>
<ul class="pagination">
<li data-bind="css: { disabled: pageIndex() === 0 }"><a href="#" data-bind="click: previousPage">&laquo;</a></li>
</ul>
<ul data-bind="foreach: allPages" class="pagination">
<li data-bind="css: { active: $data.pageNumber === ($root.pageIndex() + 1) }"><a href="#" data-bind="text: $data.pageNumber, click: function() { $root.moveToPage($data.pageNumber-1); }"></a></li>
</ul>
<ul class="pagination"><li data-bind="css: { disabled: pageIndex() === maxPageIndex() }"><a href="#" data-bind="click: nextPage">&raquo;</a></li></ul>
</div>
</div>
</td>
</tr>
</tfoot>
</table>
</div>
</div> 

3. Operation effect

Next, let’s take a look at the paging effect achieved using KnockoutJs:

4. Summary

At this point, the content to be introduced in this article ends. Although the content implemented in this article is relatively simple, for some friends who are new to KnockoutJs, I believe the implementation of this article will be a lot of guidance. Next, I will share with you the relevant content of AngularJs.

The above is the detailed explanation of the example of combining Bootstrap and KnockoutJs to achieve the paging effect introduced by the editor. I hope it will be helpful to everyone!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft