I would like to use knockout js to enable scroll pagination
Problem
I would like to pass in url and id into my `GetPage(controller, id#, page#))
Currently it is hard coded but i would like to change that.
Knockout js
$.views.Roster.GetPage = function (url, id, pageNumber) {
$.grain.Ajax.Get({
Url: url,
SectionID: {id:id},
DataToSubmit: { pageNumber: pageNumber, id: id },
DataType: "json",
OnSuccess: function (data, status, jqXHR) {
$.views.Roster.RosterViewModel.AddUsers(data);
}
});
};
Next = function () {
var _page = $.views.Roster.ViewModel.CurrentPage() + 1;
$.views.Roster.ViewModel.CurrentPage(_page);
$.views.Roster.GetPage("/api/Roster", 9, _page);
}
Scroll pagination
$(document).ready(function(){
$('#main').scroll(function () {
if ($('#main').scrollTop() >= $(document).height() - $('#main').height()) {
$('#status').text('Loading more items...' + $.views.Roster.ViewModel.TotalRoster());
if ($.views.Roster.ViewModel.RosterUsers() == null ) {
$('#status').hide();
$('#done').text('No more items...'),
$('#main').unbind('scroll');
}
setTimeout(updateStatus, 2500);
}
//updateStatus();
});
});
Change the data in getRoster function to what your server function is expecting for you to return the data. Also, remove the code $.views.Roster.GetRoster, it is not required anymore. Now when you do ko.applyBindings(new $.views.Roster.RosterViewModel()); you should get the first page of data, subsequently, when you scroll, the next() call on the view model will continue paging. That logic is all you.
$.views.Roster.RosterViewModel = function (data) {
var self = this;
self.RosterUsers = ko.observableArray([]);
_rosterUsers = self.RosterUsers;
self.currentPage = ko.observable(1);
self.toDisplay = ko.observable(10);
var filteredRoster = ko.computed(function(){
var init = (self.currentPage()-1)* self.toDisplay(),
filteredList = [],
rosterLength = self.RosterUsers().length,
displayLimit = self.toDisplay();
if(rosterLength == 0)
return[];
for(var i = init; i<(displayLimit + init) && i<rosterLength; i++)
{
filteredList.push(self.RosterUsers()[i]);
}
return filteredList;
}),
totalRoster = ko.computed(function () {
return self.RosterUsers().length;
}),
changePage = function (data) {
self.currentPage(data);
},
next = function () {
if ((self.currentPage() * self.toDisplay()) > self.RosterUsers().length)
return;
self.currentPage(self.currentPage() + 1);
},
prev = function () {
if (self.currentPage() === 1)
return;
self.currentPage(self.currentPage() - 1);
},
getRoster = ko.computed(function () {
var data = {
currentPage: self.currentPage(),
pageSize: self.toDisplay()
},
$promise = _makeRequest(data);
$promise.done(function (data) {
var localArray = [];
ko.utils.arrayForEach(data, function(d){
localArray.push(new $.views.Roster.UserViewModel(d));
});
self.RosterUsers.push.apply(self.RosterUsers,localArray);
});
}),
_makeRequest = function(data){
return $.getJSON('your url here', data);
};
};
Related
I am trying to create an observableArray of "Board" objects to populate a view.
I can currently add new Board objects to the array after each timed page refresh. But instead of clearing the array and then adding new boards from the foreach loop, it just adds to the existing ones causing duplicates.
$(document).ready(function() {
refreshPage();
});
function refreshPage() {
getGames();
setTimeout(refreshPage, 10000);
console.log("Page refreshed");
};
function Board(data) {
this.gameChannel = ko.observable(data.GameChannel);
this.HomeTeamImage = ko.observable(data.HomeTeamImage);
this.HomeTeamName = ko.observable(data.HomeTeamName);
this.HomeBeerPrice = ko.observable(data.HomeBeerPrice);
this.HomeTeamArrow = ko.observable(data.HomeTeamArrow);
this.HomeBeer = ko.observable(data.HomeBeer);
this.HomeBeerAdjustedPrice = ko.observable(data.HomeBeerAdjustedPrice);
this.AwayTeamArrow = ko.observable(data.AwayTeamArrow);
this.AwayBeerPrice = ko.observable(data.AwayBeerPrice);
this.AwayTeamName = ko.observable(data.AwayTeamName);
this.AwayBeerAdjustedPrice = ko.observable(data.AwayBeerAdjustedPrice);
this.AwayBeer = ko.observable(data.AwayBeer);
this.awayTeamImage = ko.observable(data.AwayTeamImage);
this.FullScore = ko.computed(function() {
return data.HomeTeamScore + " | " + data.AwayTeamScore;
}, this);
}
function vm() {
var self = this;
self.gameCollection = ko.observableArray([]);
}
getGames = function() {
var _vm = new vm();
$.ajax({
type: "GET",
dataType: "json",
url: "/Dashboard/PopulateMonitor/",
error: errorFunc,
success: function(data) {
_vm.gameCollection = [];
$.each(data, function() {
_vm.gameCollection.push(new Board(this));
});
}
});
function errorFunc() {
alert("Error, could not load gameboards");
}
ko.applyBindings(_vm);
}
The issue appears within the getGames() function on or around the line
_vm.gameCollection = [];
I appreciate any help available. Not very well versed with Knockout.js
Every time you're calling getGames you're creating a new '_vm':
getGames = function () {
var _vm = new vm();
Move var _vm = new vm(); to
$(document).ready(function () {
var _vm = new vm(); // <-- HERE
refreshPage();
});
Some lines have to be moved too, see the snippet :
$(document).ready(function() {
_vm = new vm();
refreshPage();
});
function refreshPage() {
getGames();
setTimeout(refreshPage, 10000);
console.log("Page refreshed");
};
function Board(data) {
this.gameChannel = ko.observable(data.GameChannel);
this.HomeTeamImage = ko.observable(data.HomeTeamImage);
this.HomeTeamName = ko.observable(data.HomeTeamName);
this.HomeBeerPrice = ko.observable(data.HomeBeerPrice);
this.HomeTeamArrow = ko.observable(data.HomeTeamArrow);
this.HomeBeer = ko.observable(data.HomeBeer);
this.HomeBeerAdjustedPrice = ko.observable(data.HomeBeerAdjustedPrice);
this.AwayTeamArrow = ko.observable(data.AwayTeamArrow);
this.AwayBeerPrice = ko.observable(data.AwayBeerPrice);
this.AwayTeamName = ko.observable(data.AwayTeamName);
this.AwayBeerAdjustedPrice = ko.observable(data.AwayBeerAdjustedPrice);
this.AwayBeer = ko.observable(data.AwayBeer);
this.awayTeamImage = ko.observable(data.AwayTeamImage);
this.FullScore = ko.computed(function() {
return data.HomeTeamScore + " | " + data.AwayTeamScore;
}, this);
}
function vm() {
var self = this;
self.gameCollection = ko.observableArray([]);
ko.applyBindings(this);
}
getGames = function() {
$.ajax({
type: "GET",
dataType: "json",
// placeholder:
url: 'data:application/json;utf8,[]',
//url: "/Dashboard/PopulateMonitor/",
error: errorFunc,
success: function(data) {
_vm.gameCollection.removeAll();
$.each(data, function() {
_vm.gameCollection.push(new Board(this));
});
}
});
function errorFunc() {
alert("Error, could not load gameboards");
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
Couple of things:
You shouldn't call applyBindings more than once. So, move it outside of your setTimeout.
_vm.gameCollection = [] won't work. To clear your observableArray, use removeAll. You can also set it to an empty array like this: _vm.gameCollection([])
Also, if you want to call the same function after an interval of time, you can make use of setInterval.
Here's a minimal version of your code. Click on Run code snippet to test it out. I have created a counter variable which updates gameCollection with new data every second.
let counter = 0;
function refreshPage() {
getGames();
console.log("Page refreshed");
};
function Board(data) {
this.gameChannel = ko.observable(data.GameChannel);
}
function vm() {
var self = this;
self.gameCollection = ko.observableArray([]);
}
getGames = function() {
let data = [
{
GameChannel: `GameChannel ${++counter}`
},
{
GameChannel: `GameChannel ${++counter}`
}];
_vm.gameCollection.removeAll(); // <- Change here
data.forEach(function(item) {
_vm.gameCollection.push(new Board(item));
});
}
var _vm = new vm();
ko.applyBindings(_vm); // this needs to be only called once per page (or element)
setInterval(refreshPage, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<!-- ko foreach: gameCollection -->
<span data-bind="text: gameChannel"></span><br>
<!-- /ko -->
I have an Upload Button in an app that uploads a deliveries object, but sometimes the deliveries object is null when it gets to the web service.
Full code is below, but it is this bit that I am having trouble unpicking. I believe this is LINQ code, so can anyone help me convert this back into a loop so that I can begin to try and understand why the deliveries object might be null?
var deliveries = Enumerable.From(results).Select(function (r) {
r.transactionDate = r.transactionDate.format("YYYY-MM-DD HH:mm:ss");
return r;
}).ToArray();
Full code:
me.uploadClicked = function () {
playClicked();
coreViewModel.busyMessage("Processing delivery data...");
deliveryRepository.GetTodaysDeliveries(function (results) {
var deliveries = Enumerable.From(results).Select(function (r) {
r.transactionDate = r.transactionDate.format("YYYY-MM-DD HH:mm:ss");
return r;
}).ToArray();
window.setTimeout(function () {
coreViewModel.busyMessage("Uploading delivery data...");
var objUploadDeliveries = Object.create({
objStore: Object.create({
storeTypeID: coreViewModel.store.storeTypeID(),
storeID: coreViewModel.store.id()
}),
objDeliveries: deliveries
});
var comm = new URLHelper();
var xhr = $.ajax({
url: comm.hosturl() + "UploadDelivery",
type: 'POST',
beforeSend: function(xh) { xh.setRequestHeader("token", coreViewModel.token); },
data: objUploadDeliveries,
dataType: 'json',
success: function (result) {
if (!result) {
playError();
return;
}
playUploadComplete();
},
error: function (x, e) {
playError();
errorHandler(x, e);
},
timeout: 60000
});
}, 20000);
});
}
The GetTodaysDeliveries function is as follows:
GetTodaysDeliveries: function (callback) {
deliverysDatabase.GetDeliveries(function (results) {
$.each(results, function (index, result) {
result.transactionDate = moment(result.transactionDate).utc();
});
var todaysResults = Enumerable.From(results).Where(function (r) {
return moment().isSame(r.transactionDate, 'day');
}).ToArray();
return callback(todaysResults);
});
}
and the deliverydatabase.GetDeliveries function inside that is as follows:
GetDeliveries: function (callback) {
var me = this;
db.transaction(
function (context) {
context.executeSql("SELECT barcode, titleName, delivered, expected, isNews, supplier, supplierId, transactionDate FROM delivery ORDER BY titlename", [], function (context, result) {
if (result.rows.length > 0) {
var results = [];
for (var i = 0; i < result.rows.length; i++) {
results.push(result.rows.item(i));
}
return callback(results);
} else {
return callback([]);
}
}, me.ErrorHandler);
}
, me.ErrorHandler);
}
Your code snippet takes the array from results, formats the date, and then returns an array. So deliverables is the same as results but with date formatted. If delivarables is null, then results must be empty or null. You can check this by inserting a
console.log("test");
into the loop
This is the unlinqd code snippet
var deliveries = [];
results.forEach(function(item)
{
var item.transactionDate = item.transactionDate.format("YYYY-MM-DD HH:mm:ss");
deliveries.push(item);
};
I hope this clears it up.
I have this grid that i am creating using knockoutjs, it works perfectly at first, now i am using a window.location.hash to run another query, it works too and query returns the correct amount of data however when i insert it within the observableArray (which gets inserted correctly as well), the grid doesn't update the data and shows the old data... I'm using removeAll() function on the observableArray as well before inserting new set of data but it wont update my grid, i suspect there is something wrong with the DOM?
I should mention when i reload the page (since the page's url keeps the hash for query) my grid shows the data and works perfectly. for some reason it needs to reload the page and doesn't work without,
Here is my JS:
if (!ilia) var ilia = {};
ilia.models = function () {
var self = this;
this.pageCount = ko.observable(0);
//this is the observableArray that i am talking about ++++++++
this.items = ko.observableArray();
var $pagination = null;
var paginationConfig = {
startPage: 1,
totalPages: 20,
onPageClick: function (evt, page) {
self.generateHash({ pageNum: page });
self.getData();
}
}
var hashDefault = {
pageNum: 1,
pageSize: 20,
catId: null,
search: ""
}
this.dataModel = function (_id, _name, _desc, _thumb, _ext) {
var that = this;
this.Id = ko.observable(_id);
this.Name = ko.observable(_name);
this.Desc = ko.observable(_desc);
this.Url = '/site/ModelDetail?id=' + _id;
var b64 = "data:image/" + _ext + ";base64, ";
this.thumb = ko.observable(b64 + _thumb);
}
this.generateHash = function (opt) {
//debugger;
var props = $.extend(hashDefault, opt);
var jso = JSON.stringify(props);
var hash = window.location.hash;
var newHash = window.location.href.replace(hash, "") + "#" + jso;
window.location.href = newHash;
return jso;
}
this.parseHash = function () {
var hash = window.location.hash.replace("#", "");
var data = JSON.parse(hash);
if (data)
data = $.extend(hashDefault, data);
else
data = hashDefault;
return data;
}
var _cntrl = function () {
var _hdnCatName = null;
this.hdnCatName = function () {
if (_hdnCatName == null)
_hdnCatName = $("hdnCatName");
return _hdnCatName();
};
var _grid = null;
this.grid = function () {
if (_grid == null || !_grid)
_grid = $("#grid");
return _grid;
}
this.rowTemplate = function () {
return $($("#rowTemplate").html());
}
}
this.createPagnation = function (pageCount, pageNum) {
$pagination = $('#pagination-models');
if ($pagination && $pagination.length > 0)
if (paginationConfig.totalPages == pageCount) return;
var currentPage = $pagination.twbsPagination('getCurrentPage');
var opts = $.extend(paginationConfig, {
startPage: pageNum > pageCount ? pageCount : pageNum,
totalPages: pageCount,
onPageClick: self.pageChange
});
$pagination.twbsPagination('destroy');
$pagination.twbsPagination(opts);
}
this.pageChange = function (evt, page) {
var hash = self.parseHash();
if (hash.pageNum != page) {
self.generateHash({ pageNum: page });
self.getData();
}
}
this.getData = function () {
var _hash = self.parseHash();
inputObj = {
pageNum: _hash.pageNum,
pageSize: _hash.pageSize,
categoryId: _hash.catId
}
//debugger;
//console.log(_hash);
if (inputObj.categoryId == null) {
ilia.business.models.getAll(inputObj, function (d) {
//debugger;
if (d && d.IsSuccessfull) {
self.pageCount(d.PageCount);
self.items.removeAll();
_.each(d.Result, function (item) {
self.items.push(new self.dataModel(item.ID, item.Name, item.Description, item.Thumb, item.Extention));
});
if (self.pageCount() > 0)
self.createPagnation(self.pageCount(), inputObj.pageNum);
}
});
}
else {
ilia.business.models.getAllByCatId(inputObj, function (d) {
if (d && d.IsSuccessfull) {
self.pageCount(d.PageCount);
self.items.removeAll();
console.log(self.items());
_.each(d.Result, function (item) {
self.items.push(new self.dataModel(item.ID, item.Name, item.Description, item.Thumb, item.Extention));
});
// initializing the paginator
if (self.pageCount() > 0)
self.createPagnation(self.pageCount(), inputObj.pageNum);
//console.log(d.Result);
}
});
}
}
this.cntrl = new _cntrl();
};
And Initialize:
ilia.models.inst = new ilia.models();
$(document).ready(function () {
if (!window.location.hash) {
ilia.models.inst.generateHash();
$(window).on('hashchange', function () {
ilia.models.inst.getData();
});
}
else {
var obj = ilia.models.inst.parseHash();
ilia.models.inst.generateHash(obj);
$(window).on('hashchange', function () {
ilia.models.inst.getData();
});
}
ko.applyBindings(ilia.models.inst, document.getElementById("grid_area"));
//ilia.models.inst.getData();
});
Would perhaps be useful to see the HTML binding here as well.
Are there any console errors? Are you sure the new data received isn't the old data, due to some server-side caching etc?
Anyhow, if not any of those:
Are you using deferred updates? If the array size doesn't change, I've seen KO not being able to track the properties of a nested viewmodel, meaning that if the array size haven't changed then it may very well be that it ignores notifying subscribers. You could solve that with
self.items.removeAll();
ko.tasks.runEarly();
//here's the loop
If the solution above doesn't work, could perhaps observable.valueHasMutated() be of use? https://forums.asp.net/t/2056128.aspx?What+is+the+use+of+valueHasMutated+in+Knockout+js
Using the google chrome Api extension, I have the following code that show notification from JSON. Once notification is show, and when I clicked on it opened multiple tabs url (It's an error). I need to solve that problem because this should open only one tab url, this is the only problem. look the code below:
var timeChange = 1000, jsons = ['JSON_URL'];
updateValue = function() {
var colorStatus = 0;
chrome.storage.local.get(function (dataStorage) {
$.getJSON(jsons+'?'+$.now(), function (data) {
var jLastPost = {'LastNotification':''}, sizePost = (data.results.length - 1), dataLastPost = data.results[0];
totalEntradas = data.totalEntradas ? data.totalEntradas : '';
$.each(data.results, function (k,v) {
if (($.inArray('post-'+v.id, dataStorage.IDs) !== -1) && (v.date_status > 0)) {
colorStatus = 1;
}
});
chrome.browserAction.setBadgeText({'text': totalEntradas.toString()});
if (dataStorage.LastNotification !== dataLastPost.id)
{
jLastPost.LastNotification = dataLastPost.id;
chrome.storage.local.set(jLastPost);
chrome.notifications.create(dataLastPost.id,{
type: 'basic',
title: dataLastPost.titulo,
message: 'Now for you!',
iconUrl: dataLastPost.image
}, function (id) {});
chrome.notifications.onClicked.addListener(function () {
chrome.tabs.create({url: dataLastPost.uri});
});
chrome.notifications.clear(dataLastPost.id, function() {});
return false;
}
});
});
setTimeout(updateValue, timeChange);
}
updateValue();
You are attaching a chrome.notifications.onClicked listener every second when you run updateValue. At a minimum you should move the listener outside of the method.
Something along these lines should work.
var timeChange = 1000, jsons = ['JSON_URL'];
var lastPostUri;
chrome.notifications.onClicked.addListener(function () {
if (lastPostUri) {
chrome.tabs.create({url: lastPostUri});
}
});
updateValue = function() {
var colorStatus = 0;
chrome.storage.local.get(function (dataStorage) {
$.getJSON(jsons+'?'+$.now(), function (data) {
var jLastPost = {'LastNotification':''}, sizePost = (data.results.length - 1), dataLastPost = data.results[0];
totalEntradas = data.totalEntradas ? data.totalEntradas : '';
$.each(data.results, function (k,v) {
if (($.inArray('post-'+v.id, dataStorage.IDs) !== -1) && (v.date_status > 0)) {
colorStatus = 1;
}
});
chrome.browserAction.setBadgeText({'text': totalEntradas.toString()});
if (dataStorage.LastNotification !== dataLastPost.id)
{
jLastPost.LastNotification = dataLastPost.id;
chrome.storage.local.set(jLastPost);
lastPostUri = dataLastPost.uri
chrome.notifications.create(dataLastPost.id,{
type: 'basic',
title: dataLastPost.titulo,
message: 'Now for you!',
iconUrl: dataLastPost.image
}, function (id) {});
chrome.notifications.clear(dataLastPost.id, function() {});
return false;
}
});
});
setTimeout(updateValue, timeChange);
}
updateValue();
I have a script that pulls data from my CMS and then allows a person to vote on a poll. The script works fine. However, I have Ad Block Plus Plugin installed in Firefox. When that is enabled to blocks the script from submitting the form correctly. It appears to submit correctly in the front end but is never registered in the back end.
Why does Ad Block Plus block my script that has nothing to do with ads?
The script is below:
$(document).ready(function () {
var Engine = {
ui: {
buildChart: function() {
if ($("#pieChart").size() === 0) {
return;
}
var pieChartData = [],
totalVotes = 0,
$dataItems = $("ul.key li");
// grab total votes
$dataItems.each(function (index, item) {
totalVotes += parseInt($(item).data('votes'));
});
// iterate through items to draw pie chart
// and populate % in dom
$dataItems.each(function (index, item) {
var votes = parseInt($(item).data('votes')),
votePercentage = votes / totalVotes * 100,
roundedPrecentage = Math.round(votePercentage * 10) / 10;
$(this).find(".vote-percentage").text(roundedPrecentage);
pieChartData.push({
value: roundedPrecentage,
color: $(item).data('color')
});
});
var ctx = $("#pieChart").get(0).getContext("2d");
var myNewChart = new Chart(ctx).Pie(pieChartData, {});
}, // buildChart
pollSubmit: function() {
if ($("#pollAnswers").size() === 0) {
return;
}
var $form = $("#pollAnswers"),
$radioOptions = $form.find("input[type='radio']"),
$existingDataWrapper = $(".web-app-item-data"),
$webAppItemName = $existingDataWrapper.data("item-name"),
$formButton = $form.find("button"),
bcField_1 = "CAT_Custom_1",
bcField_2 = "CAT_Custom_2",
bcField_3 = "CAT_Custom_3",
$formSubmitData = "";
$radioOptions.on("change", function() {
$formButton.removeAttr("disabled"); // enable button
var chosenField = $(this).data("field"), // gather value
answer_1 = parseInt($existingDataWrapper.data("answer-1")),
answer_2 = parseInt($existingDataWrapper.data("answer-2")),
answer_3 = parseInt($existingDataWrapper.data("answer-3"));
if (chosenField == bcField_1) {
answer_1 = answer_1 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_2) {
answer_2 = answer_2 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
if (chosenField == bcField_3) {
answer_3 = answer_3 + 1;
$formSubmitData = {
ItemName: $webAppItemName,
CAT_Custom_1: answer_1,
CAT_Custom_2: answer_2,
CAT_Custom_3: answer_3
};
}
prepForm($formSubmitData);
});
function prepForm(formSubmitData) {
$formButton.click(function(e) {
e.preventDefault();
logAnonUserIn("anon", "anon", formSubmitData); // log user in
}); // submit
} // prepForm
function logAnonUserIn(username, password, formSubmitData) {
$.ajax({
type: 'POST',
url: '/ZoneProcess.aspx?ZoneID=-1&Username=' + username + '&Password=' + password,
async: true,
beforeSend: function () {},
success: function () {},
complete: function () {
fireForm(formSubmitData);
}
});
} // logAnonUserIn
function fireForm(formSubmitData) {
// submit the form
var url = "/CustomContentProcess.aspx?A=EditSave&CCID=13998&OID=3931634&OTYPE=35";
$.ajax({
type: 'POST',
url: url,
data: formSubmitData,
async: true,
success: function () {},
error: function () {},
complete: function () {
window.location = "/";
}
});
}
} // pollSubmit
} // end ui
};
Engine.ui.buildChart();
Engine.ui.pollSubmit();
});
As it turns out easylist contains this filter:
.aspx?zoneid=
This is why my script is being blocked.
I was told I can try this exception filter:
##||example.com/ZoneProcess.aspx?*$xmlhttprequest
I could also ask easylist to add an exception.
Answer comes from Ad Block Plus Forums.