Bootstrap and Knockoutjs combined to realize the example of pagination effect _javascript skills

Source: Internet
Author: User

Knockoutjs is a MVVM framework for JavaScript implementations. Very good. For example, add or subtract list data items, do not need to refresh the entire control fragment or write their own JS add and delete nodes, as long as the template and the definition of the definition of the attribute can be. Simply put, we just need to focus on data access.

First, the introduction

Due to the recent company's system needs to be revised, the new system I intend to use Knockoutjs to make the Web front-end. In doing so, there is a problem-how to use Knockoutjs to complete the paging function. In the previous article, there was no introduction to using Knockoutjs to implement pagination, so in this article, you will add a knockoutjs+bootstrap to implement the paging display of the data.

Second, the use of KNOCKOUTJS implementation of pagination

Here are two ways to implement pagination, the first is to load all the data out, and then all the data paging display; the second is to load only part of the data each time, reloading the data on each request.

For both of these ways, pagination implemented using the Razor method generally uses a second way to implement pagination, but for a single-page program, the first implementation has its advantages, and the first implementation is entirely possible for not very large amounts of data, because then the subsequent data loading, The user experience is very fluent. So here are the two ways to implement each.

2.1 Implementation of partial data per load

The back-end code here uses the code from the previous article, with just a few more sample data. The specific backend implementation code is:

<summary>///Web API service, providing data Services///</summary> public class Taskcontroller:apicontroller for the Web front-end
  Private readonly Taskrepository _taskrepository = taskrepository.current; Public ienumerable<task> GetAll () {return _taskrepository.getall ().
  (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).
   (a => a.id); var pagedata = new Pagedmodel () {PageIndex = PageIndex, Pageddata = tasks.
   ToList (), TotalCount = TotalCount, PageCount = (totalcount+ pageSize-1)/pageSize};
  Returns the data return pagedata; }///<summary>///task Warehousing, encapsulating all operations on the database///</summary> public class Taskrepository {#region Static Fi LED private static lazy<taskrepository> _taskrepository = new Lazy<taskrepository> (() => new Taskreposito RY ());
  public static taskrepository Current {get {return _taskrepository.value}
    #endregion #region Fields Private readonly list<task> _tasks = new list<task> () {new Task { Id =1, Name = "Create a spa program", Description = "Spa (single page Web application), spa Advantage is a small amount of bandwidth, smooth experience", Owner = "Lea Rning hard ", Finishtime = DateTime.Parse (DateTime.Now.AddDays (1). ToString (CultureInfo.InvariantCulture))}, new Task {Id =2, Name = "Learning Knockoutjs", Description = "Kn Ockoutjs is a MVVM class library that supports bidirectional binding ", Owner =" Tommy Li ", Finishtime = DateTime.Parse (DateTime.Now.AddDays (2). ToString (CultureInfo.InvariantCulture))}, new Task {Id =3, Name = "Learning Angularjs", Description = "Ang" ULARJS is a MVVM framework that integrates MVVM and MVC. ", Owner =" Li zhi ", finishtime = DateTime.Parse (DateTime.Now.AddDays (3). ToString (CultureInfo.InvariantCulture))}, new Task {Id =4, Name = "Learning asp.net mvc Web site", Description = "Glimpse is a. NET SexAbility to test tools, support asp.net, asp.net mvc, EF, etc., the advantage is that no changes to the original project of any code, and can output code to perform the execution of all aspects of the time ", Owner =" Tonny Li ", Finishtime = DateTime . Parse (DateTime.Now.AddDays (4).
    ToString (CultureInfo.InvariantCulture))}, new Task {Id =5, Name = "Test Task 1", Description = "Test Task 1", Owner = "Li zhi", finishtime = DateTime.Parse (DateTime.Now.AddDays (5).
    ToString (CultureInfo.InvariantCulture))}, new Task {Id =6, Name = "Test Task 2", Description = "Test Task 2", Owner = "Li zhi", finishtime = DateTime.Parse (DateTime.Now.AddDays (6).
    ToString (CultureInfo.InvariantCulture))}, new Task {Id =7, Name = "Test Task 3", Description = "Test Task 3", Owner = "Li zhi", finishtime = DateTime.Parse (DateTime.Now.AddDays (7).
  ToString (CultureInfo.InvariantCulture))},};
  #endregion #region Public Methods public ienumerable<task> GetAll () {return _tasks; 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 {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}

Implementation code for the Web front-end:

@{viewbag.title = "Index2";
Layout = "~/views/shared/_layout.cshtml"; <div id= "List2" >  

The corresponding JS implementation is:

The second way to implement pagination is var ListViewModel2 = function () {//viewmodel itself.
Used to prevent the use of this when the scope is confusing var self = this;
Self.loadingstate = Ko.observable (true);
Self.pagesize = ko.observable (3);
Data This.pagedlist = Ko.observablearray ();
The page number to be accessed This.pageindex = ko.observable (1);
Total pages This.pagecount = ko.observable (1);
Number of pages This.allpages = Ko.observablearray ();
Current page This.currengepage = ko.observable (1);
Self.totalcount = ko.observable (1); This.refresh = function () {//Limit request page number within the range of data page number if (Self.pageindex () < 1) self.pageindex (1); if (Self.pageindex () > SE Lf.pagecount ()) {Self.pageindex (Self.pagecount ());}//post asynchronously loads the data sendajaxrequest ("Get", function (data) {////load new data before
First remove the original 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++) {//Reload page number Self.allPages.push ({pagenumber:i});}//for...in statements are used for the properties of an array or object
Loop operation. The code in the for ... in loop performs one operation on the elements of the array or on the properties of the object each time it executes。 for (var i in data.pageddata) {//Reload Data Self.pagedList.push (Data.pageddata[i]);}}, ' Getbypaged ', {' PageIndex ': self.page
Index ()});
};
Request first page Data This.first = function () {self.pageindex (1); Self.refresh ();};
Request Next page Data This.next = function () {Self.pageindex (This.pageindex () + 1); Self.refresh ();
Request a previous page of data this.previous = function () {Self.pageindex (This.pageindex ()-1); Self.refresh ();};
Request last page Data This.last = function () {Self.pageindex (This.pagecount ()-1), Self.refresh ();};
Jump to a page this.gotopage = function (data, event) {self.pageindex (data); Self.refresh ();};
}; function Sendajaxrequest (HttpMethod, callback, URL, reqdata) {$.ajax ("/api/task" + URL?)
"/" + URL: ""), {type:httpmethod, Success:callback, data:reqdata}); $ (document). Ready (function () {var viewModel = new ListViewModel2 (); Viewmodel.refresh (); if ($ (' #list2 '). Length) Ko.app
Lybindings (ViewModel, $ (' #list2 '). Get (0));  });

This paper introduces the realization of paging function by using Knockoutjs in the following ways:

1. After the page load completes, the AJAX request is initiated to invoke the rest service asynchronously to request some data.

2. Then the requested data is displayed by Knockoutjs binding.

3. Bind the corresponding paging information to the bootstrap page

4. When the user clicks the page, another AJAX request is made to invoke the rest service request data asynchronously, and then the requested data is displayed.

This is the description of the code called the logical relationship, you can refer to the corresponding JS code to understand the above description. The second way to achieve this is done.

2.2 Load all data for the first time and then page all the data

This is the first way to implement the this implementation, the user will only be in the first time will feel the data loading, the page in the process of feeling not to load, so for some of their own data is not too many circumstances, the user's feeling is more fluent.

The specific implementation of the idea, that is, the requested data should not be all displayed on the page, because the data is too much, suddenly displayed to the page, users may be dazzled. Paging the data will make the user more visible.

The implementation code for the specific Web front-end JS is:

var Listviewmodel = function () {var self = this; Window.viewmodel = self; self.list = Ko.observablearray (); Self.pagesi 
Ze = ko.observable (3); Self.pageindex = ko.observable (0); The page number to be accessed Self.totalcount = ko.observable (1);
Total number of records self.loadingstate = Ko.observable (true); Self.pagedlist = ko.dependentobservable (function () {var size = self.pagesize (); var start = Self.pageindex () * size; ret
Urn 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 to 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" >  

Third, the Operation effect

Next, let's take a look at the paging effect implemented using Knockoutjs:

Iv. Summary

Here, this article to introduce the end of the content, although the content of the implementation of this article is relatively simple, but for some just contact Knockoutjs friends, I believe this implementation of this article will be a lot of guidance. Next, I will share with you the relevant content of ANGULARJS.

The above is a small set to introduce the bootstrap and Knockoutjs combined to achieve a detailed example of pagination effect, I hope to help you!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.