I am not getting the concepts of how pagination works in load more requested data from json api. Even i am getting the data of first page but for remaining pages not getting. If I am using the two api for paging and fetching data but still not getting. Any one help me clear this concepts please..
main-view-model.js
const httpModule = require("tns-core-modules/http");
var observableModule = require("tns-core-modules/data/observable");
function RegisterViewModel() {
var viewModel = observableModule.fromObject({
_sourceDataItems: [],
initDataItems: function () {
//This url for the pagination
var url1 = "https://example.org/api.php?action=query&gcmtitle=Category:xyz&pilimit=max&prop=pageimages&pithumbsize=200&generator=categorymembers&format=json&gcmcontinue=";
httpModule.getJSON(url1).then((r) => {
id = r.continue.gcmcontinue
gcm.push(id)
console.log(gcm)
var pageid = [];
for (var id in r.query.pages) {
pageid.push(id);
}
for (var i = 0; i < pageid.length; i++) {
if (r.query.pages[pageid[i]].thumbnail == null) {
let abc = {
ttt: r.query.pages[pageid[i]].title,
path1: "~/images/xyz.png"
}
this._sourceDataItems.push(abc)
}
else {
let aaa = {
ttt: r.query.pages[pageid[i]].title,
path1: r.query.pages[pageid[i]].thumbnail.source
}
this._sourceDataItems.push(aaa)
}
}
}, (e) => {
});
var gcm = [];
//This url for the fetching the data on scroll
for (var i = 0; i < gcm.length; i++) {
var url2 = "https://example.org/api.php?action=query&gcmtitle=Category:xyz&pilimit=max&prop=pageimages&pithumbsize=200&generator=categorymembers&format=json&gcmcontinue=" + gcm[i];
httpModule.getJSON(url2).then((r) => {
id= r.continue.gcmcontinue)
gcm.push(id)
console.log(r.continue.gcmcontinue)
var pageid = [];
for (var id in r.query.pages) {
pageid.push(id);
}
for (var i = 0; i < pageid.length; i++) {
//placeholder Image
if (r.query.pages[pageid[i]].thumbnail == null) {
let abc = {
ttt: r.query.pages[pageid[i]].title,
path1: "~/images/xyz.png"
}
this._sourceDataItems.push(abc)
}
else {
let aaa = {
ttt: r.query.pages[pageid[i]].title,
path1: r.query.pages[pageid[i]].thumbnail.source
}
this._sourceDataItems.push(aaa)
}
}
}, (e) => {
});
}
},
_DataItems: [],
addMoreItemsFromSource: function (chunkSize) {
let newItems = this._sourceDataItems.splice(0, chunkSize);
this._DataItems = this._DataItems.concat(newItems);
},
onLoadMoreItemsRequested: function (args) {
console.log("---load item called----");
const that = new WeakRef(this);
const listView = args.object;
if (this._sourceDataItems.length > 0) {
setTimeout(function () {
that.get().addMoreItemsFromSource(5);
listView.notifyLoadOnDemandFinished();
}, 100);
args.returnValue = true;
} else {
args.returnValue = false;
}
},
});
return viewModel;
}
exports.RegisterViewModel = RegisterViewModel;
Even loading of the data is working fine for page one. While passing the gcm continue id it wont take that please help me to clear this concept
Related
I have a problem when using await in a for loop. Every time it hits the await funtion it executes it fine, but it stops loping through the rest of the array that is looping through. I'm using nodejs with axios to send http request to a restAPI. The function that is in the api is big. So I thought maby that is the problem but it wasn't. Also the api uses its own await functions to, but that wasn't the problem either(As far as I know).
Here is my code for the request
var files = await globPromise("assets/series/**/*.json");
var json = null;
var file = null;
var series = [];
for (i = 0; i < files.length; i++) {
file = files[i];
var raw = fs.readFileSync(file);
json = JSON.parse(raw);
if (json.type === "series") {
try {
var userId = null;
if (req.user == null) {
userId = req.query.userid;
} else {
userId = req.user.id;
}
const response = await axios.get("http://" + host + "/series/info/" + json.id + "?userid=" + userId);
series.push(JSON.parse(response.data));
} catch (error) {
console.log(error);
series.push(json);
}
}
}
res.json(JSON.stringify(series));
});
And also the api side:
app.get('/series/info/:id', async(req, res) => {
var files = await globPromise("assets/series/**/*.json");
var json = null;
var file = null;
for (i = 0; i < files.length; i++) {
file = files[i];
var raw = fs.readFileSync(file);
json = JSON.parse(raw);
if (json.type === "series" && json.id === req.params.id) {
break;
}
json = null;
}
let path = pathFs.dirname(file) + "/";
try {
var seriesFiles = await fsPromise.readdir(path);
var latestWatchedVideo = null;
var latestWatchedTime = null;
var latestWatchTime = null;
var latestWatchDuration = null;
var seasonCount = 0;
var seasons = [];
for (i = 0; i < seriesFiles.length; i++) {
seriesFile = seriesFiles[i];
if (fs.lstatSync(path + "/" + seriesFile).isDirectory()) {
if (!seriesFile.startsWith("s")) {
continue;
}
seasonCount++;
try {
var videoFiles = await fsPromise.readdir(path + "/" + seriesFile + "/");
var videos = [];
for (let i = 0; i < videoFiles.length; i++) {
const video = videoFiles[i];
if (video.endsWith(".json")) {
var rawVideo = fs.readFileSync(path + "/" + seriesFile + "/" + video);
videoJson = JSON.parse(rawVideo);
const query = util.promisify(con.query).bind(con);
var userId = null;
if (req.user == null) {
userId = req.query.userid;
} else {
userId = req.user.id;
}
var results = await query(`SELECT * FROM watched WHERE video_id = "${videoJson.id}" AND user_id = "${userId}"`);
if (results.length > 0) {
var updated = JSON.parse(JSON.stringify(results[0].updated));
var duration = JSON.parse(JSON.stringify(results[0].duration));
var time = JSON.parse(JSON.stringify(results[0].time));
if (latestWatchedVideo == null) {
latestWatchedVideo = videoJson.id;
latestWatchedTime = updated;
latestWatchTime = time;
latestWatchDuration = duration;
} else {
if (latestWatchedTime < updated) {
latestWatchedVideo = videoJson.id;
latestWatchedTime = updated;
latestWatchTime = time;
latestWatchDuration = duration;
}
}
}
videos.push(videoJson);
}
}
function compare(a, b) {
if (a.episode < b.episode) {
return -1;
}
if (a.episode > b.episode) {
return 1;
}
return 0;
}
videos.sort(compare);
seasons.push({
season: seasonCount,
title: seriesFile.replace("s" + seasonCount, ""),
videos: videos
});
} catch (error) {
console.log(error);
}
}
}
json.seasonCount = seasonCount;
json.seasons = seasons;
json.latestWatchDuration = latestWatchDuration;
json.latestWatchTime = latestWatchTime;
json.latestWatchedVideo = latestWatchedVideo;
json.latestWatchedTime = latestWatchedTime;
res.json(JSON.stringify(json));
} catch (error) {
console.log(error);
}
});
Is there something (important) about await and async that I've missed?
Edit: my problem is that is loops fine through the first item and the await is working fine too, but it stops the loop and executes the next lines of code like there are no other items in my array.
Solved: I tried using the for/of and it works now. I don't know whats is so different between de default for and this one but it works!
So, I made a method fetchStories that fetches stories from my API in batches of 10, and the new stories can be fetched once you've scrolled to the bottom of the screen. This is what part of my Vue instance looks like:
var discoveryFeed = new Vue({ // eslint-disable-line no-unused-vars
el: '#discoveryFeed',
data: {
userId: userId,
username: username,
tags: [],
selectedTag: null,
stories: [],
checklist: [],
limit: 10,
page: 1,
isEnd: false,
busy: false,
isFollowing: true
},
beforeMount: function() {
var self = this;
self.$http.get('/api/tags')
.then(function(res) {
self.tags = res.body;
}, function(err) {
self.tags = [];
});
self.$http.get('/api/user/' + self.username + '/checklist')
.then(function(res) {
self.checklist = res.body || [];
}, function(err) {
self.checklist = [];
});
self.fetchStories();
},
methods: {
fetchStories: function(isNew) {
var self = this;
isNew = Boolean(isNew);
if(self.isEnd) { return; }
self.busy = true;
var url = '/api/discover';
if(self.selectedTag) {
url = `/api/tags/${self.selectedTag.code}/stories`;
}
url += '?p=' + self.page;
url += '&l=' + self.limit;
self.page += 1;
self.$http.get(url)
.then(function(res) {
self.busy = false;
if(res.body.length === 0) {
self.isEnd = true;
return;
}
if(isNew) {
self.stories = [];
}
self.stories = self.stories.concat(res.body);
}, function(err) {
self.busy = false;
self.stories = [];
});
},
setTag: function(tag) {
var self = this;
self.selectedTag = tag;
for(var i = 0; i < self.tags.length; i++) {
self.tags[i].selected = false;
}
self.selectedTag.selected = true;
self.page = 1;
self.fetchStories(true);
}
In my pug, I'm using the v-infinite-scroll directive to call the method fetchStories. Also note that I'm working with a list of tags, and clicking a new tag will load different sets of stories through the method setTag(tag).
nav.col-lg-3.col-md-4.d-none.d-md-block.d-lg-block.bg-sidebar(v-cloak)
.feed-sidebar.feed-sidebar-interests.border-top-0.border-bottom-0.border-left-0.position-sticky
strong Your Interests
div.list-group.list-unstyled.mt-2(v-if="tags.length > 0")
a.tag-btn.mb-2.align-middle.text-black(v-for="tag, index in tags" v-bind:class="{ active: selectedTag && selectedTag.id === tag.id }" #click="setTag(tag); scrollToTop();")
i.fa-fw.mr-2(v-bind:class="tag.icon + ' fa-lg'"
v-bind:style="'color:' + tag.hexColor")
span {{ tag.name }}
.col-lg-6.col-md-8(v-cloak
v-infinite-scroll="fetchStories"
infinite-scroll-disabled="busy"
infinite-scroll-distance="50")
Upon checking the data response at the initial load, the ten stories are fetched at /stories?p=1&l=10. However, upon reaching the bottom the data response array of /stories?p=2&l=10 is empty. This may have something to do with my use of booleans to set flags when choosing a tag.
Apparently, I should have reset the value of isEnd when I'm setting the new tag.
setTag: function(tag) {
var self = this;
self.selectedTag = tag;
for(var i = 0; i < self.tags.length; i++) {
self.tags[i].selected = false;
}
self.selectedTag.selected = true;
self.page = 1;
self.isEnd = false;
self.fetchStories(true);
}
I am migrating from js to angular and have come across a weird situation, I had designed my DOM to convert all the HTML Select tag to UL using this JS script:
var coaching = function() {}
coaching.prototype.customSelect = function(wrapper) {
wrapper.querySelectorAll('.form-ctrl').forEach(function(elm) {
if (elm.tagName == 'SELECT') {
var allOptions = elm.getElementsByTagName('option');
var allreadyCustomDropDown =
elm.parentNode.querySelector('.customDropdown');
if (allreadyCustomDropDown != null) {
allreadyCustomDropDown.remove();
}
if (allOptions.length > 0) {
var listWrapper = document.createElement('ul');
listWrapper.classList.add('customDropdown');
for (var i = 0; i < allOptions.length; i++) {
var list = document.createElement('li');
list.innerHTML = allOptions[i].innerHTML;
listWrapper.appendChild(list);
}
elm.parentNode.appendChild(listWrapper);
elm.parentNode.classList.add('customSelectWrapper');
listWrapper.querySelectorAll('li').forEach(function(liList) {
liList.addEventListener('click', function() {
liList.parentNode.parentNode.querySelector('.form-
ctrl').value = liList.innerHTML;
liList.parentNode.parentNode.classList.add('has-value');
liList.parentNode.classList.remove('visibleDropdown');
liList.parentNode.parentNode.querySelector('.form-ctrl').style.opacity = 1;
})
})
}
// listWrapper.addEventListener
}
});
wrapper.querySelectorAll('select.form-ctrl').forEach(function(elm) {
elm.addEventListener('click', function() {
document.querySelectorAll('.customDropdown').forEach(function(elm1) {
elm1.parentNode.querySelector('.customDropdown').classList.remove('visibleDropdown');
});
elm.style.opacity = 0;
elm.parentNode.querySelector('.customDropdown').classList.add('visibleDropdown');
});
});
document.addEventListener('click', (e) => {
if (!e.target.parentNode.classList.contains('customDropdown') && !e.target.parentNode.classList.contains('customSelectWrapper')) {
document.querySelectorAll('.customDropdown').forEach(function(elm) {
elm.classList.remove('visibleDropdown');
elm.parentNode.querySelector('.form-ctrl').style.opacity = 1;
});
}
});
}
var coachingInstance = new coaching();
coachingInstance.customSelect(document);
Now on HTML side I use a wrapper on the select tag
<div class="field-wrapper">
<select id="enquiryPriority" class="form-ctrl" [(ngModel)]="advancedFilterForm.priority" name="priority" formInput>
<option></option>
<option *ngFor="let priority of enqPriority" [value]="priority.data_key">
{{priority.data_value}}
</option>
</select>
<label for="enquiryPriority">Enquiry Priority</label>
</div>
My question is how can I perform this conversion on Document load in angular since typescript throws an error when I use querySelectorAll('.form-ctrl').forEach() and many other common functions that I was able to use in plain javascript.
Update ==> Tried to perform the action using a function on ngOnInit
convertSelectToUl() {
var myNodeListOne = document.querySelectorAll('.form-ctrl');
[].forEach.call(myNodeListOne, function (elm) {
if (elm.tagName == 'SELECT') {
var allOptions = elm.getElementsByTagName('option');
var allreadyCustomDropDown =
elm.parentNode.querySelector('.customDropdown');
if (allreadyCustomDropDown != null) {
allreadyCustomDropDown.remove();
}
if (allOptions.length > 0) {
var listWrapper = document.createElement('ul');
listWrapper.classList.add('customDropdown');
for (var i = 0; i < allOptions.length; i++) {
var list = document.createElement('li');
list.innerHTML = allOptions[i].innerHTML;
listWrapper.appendChild(list);
}
elm.parentNode.appendChild(listWrapper);
elm.parentNode.classList.add('customSelectWrapper');
var listNode = listWrapper.querySelectorAll('li');
[].forEach.call(listNode, function (liList) {
liList.addEventListener('click', function () {
liList.parentNode.parentNode.querySelector('.form-ctrl').value = liList.innerHTML;
liList.parentNode.parentNode.classList.add('has-value');
liList.parentNode.classList.remove('visibleDropdown');
liList.parentNode.parentNode.querySelector('.form-ctrl').style.opacity = 1;
})
})
}
}
});
var myNodeListTwo = document.querySelectorAll('select.form-ctrl');
[].forEach.call(myNodeListTwo, function (elm) {
elm.addEventListener('click', function () {
var listDropdown = document.querySelectorAll('.customDropdown');
[].forEach.call(listDropdown, function (elm1) {
elm1.parentNode.querySelector('.customDropdown').classList.remove('visibleDropdown');
});
elm.style.opacity = 0;
elm.parentNode.querySelector('.customDropdown').classList.add('visibleDropdown');
});
});
document.addEventListener('click', (e) => {
let parent = (<HTMLElement>(<HTMLElement>e.target).parentNode);
if (!parent.classList.contains('customDropdown')
&& !parent.classList.contains('customSelectWrapper')) {
var nodeDropdown = document.querySelectorAll('.customDropdown');
[].forEach.call(nodeDropdown, function (elm) {
elm.classList.remove('visibleDropdown');
elm.parentNode.querySelector('.form-ctrl').style.opacity = 1;
});
}
});
}
Just converted your JS code into TS, please try to run the same.
declare let document: any;
export class Coching {
customSelect(wrapper) {
wrapper.querySelectorAll('.form-ctrl').forEach((elm) => {
if (elm.tagName === 'SELECT') {
const allOptions = elm.getElementsByTagName('option');
const allreadyCustomDropDown =
elm.parentNode.querySelector('.customDropdown');
if (allreadyCustomDropDown != null) {
allreadyCustomDropDown.remove();
}
if (allOptions.length > 0) {
const listWrapper = document.createElement('ul');
listWrapper.classList.add('customDropdown');
for (let i = 0; i < allOptions.length; i++) {
const list = document.createElement('li');
list.innerHTML = allOptions[i].innerHTML;
listWrapper.appendChild(list);
}
elm.parentNode.appendChild(listWrapper);
elm.parentNode.classList.add('customSelectWrapper');
listWrapper.querySelectorAll('li').forEach((liList) => {
liList.addEventListener('click', () => {
liList.parentNode.parentNode.querySelector('.form-ctrl').value = liList.innerHTML;
liList.parentNode.parentNode.classList.add('has-value');
liList.parentNode.classList.remove('visibleDropdown');
liList.parentNode.parentNode.querySelector('.form-ctrl').style.opacity = 1;
})
})
}
// listWrapper.addEventListener
}
});
wrapper.querySelectorAll('select.form-ctrl').forEach((elm) => {
elm.addEventListener('click', function () {
document.querySelectorAll('.customDropdown').forEach((elm1) => {
elm1.parentNode.querySelector('.customDropdown').classList.remove('visibleDropdown');
});
elm.style.opacity = 0;
elm.parentNode.querySelector('.customDropdown').classList.add('visibleDropdown');
});
});
document.addEventListener('click', (e) => {
if (!e.target.parentNode.classList.contains('customDropdown') && !e.target.parentNode.classList.contains('customSelectWrapper')) {
document.querySelectorAll('.customDropdown').forEach((elm) => {
elm.classList.remove('visibleDropdown');
elm.parentNode.querySelector('.form-ctrl').style.opacity = 1;
});
}
});
}
}
Need help with the chaining. The functions work. But async calls make it hard for me to get everything. Help me think right!
My thought:
Get All Webs recursively (function works)
Get all lists from webs and iff announcementlist add to array and pass along
Get two items from all announcmentlists and sort by created.
Add ALL announcement items into one large array (to be able to sort array later.
Heres the code,
function getAllWebs(success, error) {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_site().get_rootWeb();
var result = [];
var level = 0;
result.push(web);
var getAllWebsInner = function (web, result, success, error) {
level++;
var ctx = web.get_context();
var webs = web.get_webs();
ctx.load(webs, 'Include(Title,Webs,ServerRelativeUrl)');
ctx.executeQueryAsync(
function () {
for (var i = 0; i < webs.get_count() ; i++) {
var web = webs.getItemAtIndex(i);
result.push(web);
if (web.get_webs().get_count() > 0) {
getAllWebsInner(web, result, success, error);
}
}
level--;
if (level == 0 && success)
success(result);
},
error);
};
getAllWebsInner(web, result, success, error);
}
function error(sender, args) {
console.log(args.get_message());
};
function getAnnouncementLists(web, success, error) {
var dfd = $.Deferred();
var ctx = web.get_context();
var collList = web.get_lists();
var result = []
ctx.load(collList, 'Include(Title, Id, BaseTemplate)');
ctx.executeQueryAsync(function () {
for (var i = 0; i < collList.get_count() ; i++) {
var list = collList.getItemAtIndex(i);
var bTemp = list.get_baseTemplate();
if (bTemp == 104) {
result.push(list);
}
}
//success(result);
dfd.resolve(result);
}, error);
return dfd.promise();
}
function getListItems(list, success, error) {
var dfd = $.Deferred();
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View><Query><OrderBy><FieldRef Name="Created" Ascending="False"></FieldRef>'
+ '</OrderBy></Query><ViewFields><FieldRef Name="Title"/><FieldRef Name="Body"/>' +
'<FieldRef Name="Created"/></ViewFields><RowLimit>2</RowLimit></View>');
var listItems = list.getItems(camlQuery);
var result = []
var ctx = list.get_parentWeb().get_context();
ctx.load(listItems);
ctx.executeQueryAsync(function () {
for (var i = 0; i < listItems.get_count() ; i++) {
var item = listItems.getItemAtIndex(i);
result.push(item);
}
dfd.resolve(result);
//success(result);
}, error);
return dfd.promise();
}
function printResults(items) {
var sortedItems = items.sort(dynamicSort("get_created()"));
alert(sortedItems);
}
function dynamicSort(property) {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a, b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
$(document).ready(function () {
var items = getAllWebs(
function (allwebs) {
var array = [];
for (var i = 0; i < allwebs.length; i++) {
getAnnouncementLists(allwebs[i]).then(function (announceLists) {
for (var i = 0; i < announceLists.length; i++) {
getListItems(announceLists[i]).then(function (items) {
array.push(items);
});
}
});
}
return array;
}
);
//getAllWebs(
// function (allwebs) {
// for (var i = 0; i < allwebs.length; i++) {
// getAnnouncementLists(allwebs[i],
// function (announceLists) {
// for (var i = 0; i < announceLists.length; i++) {
// getListItems(announceLists[i],
// function (items) {
// printResults(items);
// }, error);
// }
// }, error);
// }
// }, error);
});
Given the requirements to retrieve list items from Announcements lists located across site collection, below is demonstrated the modified example that contains some improvements such as:
the number of requests to the server is reduced
fixed the issue in getAllWebs function that prevents to return any results if site contains only a root web
Example
function getAllWebs(propertiesToRetrieve,success, error) {
var ctx = SP.ClientContext.get_current();
var web = ctx.get_site().get_rootWeb();
var result = [];
var level = 0;
ctx.load(web, propertiesToRetrieve);
result.push(web);
var getAllWebsInner = function (web, result, success, error) {
level++;
var ctx = web.get_context();
var webs = web.get_webs();
var includeExpr = 'Include(Webs,' + propertiesToRetrieve.join(',') + ')';
ctx.load(webs, includeExpr);
ctx.executeQueryAsync(
function () {
for (var i = 0; i < webs.get_count() ; i++) {
var web = webs.getItemAtIndex(i);
result.push(web);
if (web.get_webs().get_count() > 0) {
getAllWebsInner(web, result, success, error);
}
}
level--;
if (level == 0 && success)
success(result);
},
error);
};
getAllWebsInner(web, result, success, error);
}
function loadListItems(lists,query,success,error,results){
var results = results || [];
var curList = lists[0];
var ctx = curList.get_context();
var listItems = curList.getItems(query);
ctx.load(listItems);
ctx.executeQueryAsync(function () {
results.push.apply(results, listItems.get_data());
lists.shift();
if(lists.length > 0) {
loadListItems(lists,query,success,error,results);
}
if(lists.length == 0)
success(results);
}, error);
}
function dynamicSort(property) {
var sortOrder = 1;
if (property[0] === "-") {
sortOrder = -1;
property = property.substr(1);
}
return function (a, b) {
var result = (a[property] < b[property]) ? -1 : (a[property] > b[property]) ? 1 : 0;
return result * sortOrder;
}
}
var propertiesToRetrieve = ['Lists.Include(BaseTemplate)','ServerRelativeUrl'];
getAllWebs(propertiesToRetrieve,
function(allwebs){
//1. get filtered lists
var allAnnouncementLists = [];
allwebs.forEach(function(w){
var announcementLists = w.get_lists().get_data().filter(function(l){
if(l.get_baseTemplate() == SP.ListTemplateType.announcements)
return l;
});
allAnnouncementLists.push.apply(allAnnouncementLists, announcementLists);
});
//2.Load list items from lists
var query = new SP.CamlQuery(); //<-set your custom query here
loadListItems(allAnnouncementLists,query,
function(allListItems){
//3.Sort and print results
var sortedItems = allListItems.sort(dynamicSort("get_created()"));
sortedItems.forEach(function(item){
console.log(item.get_item('Title'));
});
},logError);
},
logError);
function logError(sender,args){
console.log(args.get_message());
}
I build a prototype that handle pages, I successfully add (push), but can get the data, I failed:
var foundImageIndex = Pages.indexFirst(function (item) { if (item.PageID == PageID) return true; });
Here the javascript page handler:
var Pages = new Array();
PageContainer = function () //constructor for the proxy
{
// this._baseURL = url;
};
PageContainer.prototype =
{
AddPage: function (data) {
if (data == null) return;
Pages.push({ PageID: data.PageID, SegmentID: data.SegmentID });
},
GetPage: function (PageID) {
alert('getPage('+PageID+')=' + JSON.stringify(Pages));
var foundImageIndex = Pages.indexFirst(function (item) { if (item.PageID == PageID) return true; });
var dt = { PageID: Pages[foundImageIndex].PageID, SegmentID: Pages[foundImageIndex].SegmentID };
return dt;
}
};
I call from other js as following:
var gPageContainer = new PageContainer();
for (var i = 0; i < SegStruct.SegmentsCount; i++) {
var segRClass = //get from webservice
gPageContainer.AddPage({ PageID: i, SegmentID: segRClass.SegmentID });
}
I trying to call: gPageContainer.GetPage(1); but it failed in GetPage: function (PageID) it returns -1 in:
var foundImageIndex = Pages.indexFirst(function (item) { if (item.PageID == PageID) return true; });
foundImageIndex always -1
why?
Simply add the following before the constructor:
if (typeof Array.prototype.indexFirst == 'undefined') {
Array.prototype.indexFirst = function (validator) {
for (var i = 0; i <= this.length - 1; i++) {
if (validator(this[i])) {
return i;
}
}
return -1;
};
}