Getting bug in recursive functions? - javascript

I am using an array with nested object of array. Assigning the values in array's values according to input line index, values are passed into the array's indexed value. I have checked the condition that if in array object is there, it converts it into array and call the recursive function and it calls recursion until the object's array's value is full but don't know why it is not working properly. Please help me in this bug
(function($) {
var xmlOutput = document.querySelector(".xmlOutput");
let templateStore = [];
let preservedEntriesValue = [];
let selectedTemplate = [];
function generateDOMDropdown(selectedID) {
let optionTemplate = templateStore.map(function(entry) {
return `<option value="${
entry.id
}" ${entry.id === selectedID ? "selected" : ""}>${entry.name}</option>`;
});
$("#select").html(optionTemplate);
}
function processEntries(entries) {
let output = "";
for (const entry of entries) {
output += entry;
}
return output;
}
function parseJSONToXML(input) {
const domStructure = input.entriesValue.map(function(tagObj) {
if (typeof tagObj === "string") {
return `<${tagObj}></${tagObj}>`;
} else if (Array.isArray(tagObj)) {
if (tagObj.length > 1) {
return `<${tagObj[0]}>${tagObj[1]}</${tagObj[0]}>`;
} else if (tagObj.length == 1) {
return `<${tagObj[0]}></${tagObj[0]}>`;
}
} else {
const outerTag = Object.keys(tagObj).pop();
const innerDOM = parseJSONToXML({ entriesValue: tagObj[outerTag] });
return `<${outerTag}>${processEntries(innerDOM)}</${outerTag}>`;
}
});
return domStructure;
}
function preFillSelected() {
const root = selectedTemplate.root;
const domStructure = parseJSONToXML(selectedTemplate);
xmlOutput.innerText = vkbeautify.xml(
`<?xml version="1.0" encoding="UTF-8"?><${root}>${processEntries(
domStructure
)}</${root}>`,
5
);
}
$.ajax({
type: "get",
url: window.location.origin + "/templates.json",
success: function(data) {
templateStore = data;
if (data.length > 0) {
selectedTemplate = data[0];
generateDOMDropdown(selectedTemplate.id);
preservedEntriesValue = selectedTemplate.entriesValue;
preFillSelected();
$("#select")
.off("change")
.on("change", function() {
selectedTemplate = templateStore[$("#select").val()];
preservedEntriesValue = selectedTemplate.entriesValue;
preFillSelected();
window.template = selectedTemplate;
});
}
}
});
function generateValueJSON(
template,
lines,
inputLen,
templateLen,
flatLen,
cidx
) {
cidx = cidx || 0;
// console.log('Entry', lines, template, cidx);
return Array.from(template.entriesValue.entries()).map(([idx, entry]) => {
console.log("Lines", lines);
if (idx < lines.length) {
if (Array.isArray(entry)) {
return [entry[0], lines[idx]];
} else if (typeof entry === "object") {
// debugger;
const outerTag = Object.keys(entry).pop();
const innerLength = entry[outerTag].length;
if (cidx === 0) cidx = idx;
const outerIdx = cidx + innerLength;
// console.log((flatLen - templateLen - inputLen));
// console.log({ flatLen, templateLen, inputLen, outerIdx, cidx, idx });
const innerObj = generateValueJSON(
{ entriesValue: entry[outerTag] },
lines.slice(idx, outerIdx),
inputLen,
templateLen,
flatLen,
idx
);
// cidx = 0;
entry[outerTag] = innerObj;
return entry;
}
return [entry, lines[idx]];
}
return entry;
});
}
function mapLength(template) {
return template.entriesValue
.map((entry) => {
return typeof entry === "object"
? [Object.keys(entry), Object.values(entry)]
: entry;
})
.flat(3).length;
}
$("#txtInput").on("keyup", function() {
const lines = $(this)
.val()
.split("\n\n")
.map((v) => v.trim().replace(/\n/g, "<br/>"));
// console.log(preservedEntriesValue);
selectedTemplate.entriesValue = preservedEntriesValue;
templateLength = mapLength(selectedTemplate);
const newEntriesValue = generateValueJSON(
selectedTemplate,
lines,
lines.length,
selectedTemplate.entriesValue.length,
templateLength
);
// console.log(newEntriesValue);
selectedTemplate.entriesValue = newEntriesValue;
preFillSelected();
});
})(window.jQuery, Node);
//here is the data array
[{
"id": "1",
"name": "Template Name 2",
"root": "media",
"entriesValue": [
"mediaid",
"category",
"provider",
"date",
"caption_photo_1",
{
"image": [
"imageid",
"type",
"width",
"hfive"
]
},
{
"video": [
"name",
"type",
"bitrate",
"size",
"width",
"hfive",
"headline",
"summary"
]
}
]
},
{
"id": "0",
"name": "Template Name 1",
"root": "article",
"entriesValue": [
"author",
"headline",
"cats",
"subcats",
"image",
"video",
"tags",
"summary",
"content"
]
},
{
"id": "2",
"name": "Template Name 3",
"root": "article",
"entriesValue": [
"author",
"headline",
"cats",
"subcats",
"image",
"video",
"summary",
"content",
"keyword"
]
},
{
"id": "3",
"name": "Template Name 4",
"root": "root",
"entriesValue": [
"description",
"title",
"languageId",
"categoryIds"
]
}
]
At first input it work properly but in second input it passes the value in in both object
<image>
<imageid>Correct</imageid>
<type>bug</type>
<width>bug</width>
<hfive></hfive>``
</image>
<video>
<name>bug</name>
<type>bug</type>
<bitrate></bitrate>
<size></size>
<width></width>
<hfive></hfive>
<headline></headline>
<summary></summary>
</video>

Related

How to get the parent object value using child value

I have value "b" with me and I want to get the item "3648" using that how can I do that using JavaScript?
{
"someID": "16385421",
"items": {
"9836": {
"id": "a"
},
"3648": {
"id": "b"
},
"7738": {
"id": "c"
}
}
}
o/p
"3648": {
"id": "b"
}
Edited after your comment:
getByItemId = ( val ) => {
let result;
for( let elem in data.items ){
const check = data.items[ elem ];
if( check.id == val ) result = check;
}
console.log( result )
return result;
}
getByItemId( "b" )
You could do it with some code that resembled the following.
First we get all of the object keys in the obj.items object.
Next we iterate through them.
At each step, we check to see if the desired ID is contained within the sub-object indexed by the current key in the array. If it's found, we update the result object.
We then return an empty object if the key isn't present, and something like the following if it was found: {key: '3648', id: 'b'}.
"use strict";
function byId(id){return document.getElementById(id)}
function qs(sel,parent=document){return parent.querySelector(sel)}
function qsa(sel,parent=document){return parent.querySelectorAll(sel)}
window.addEventListener('load', onLoaded, false);
var rawData = {
"someID": "16385421",
"items": {
"9836": {
"id": "a"
},
"3648": {
"id": "b"
},
"7738": {
"id": "c"
}
}
};
function getIDs(data, searchItemId)
{
let keys = Object.keys(data.items);
let result = {};
keys.forEach( keyFunc );
return result;
function keyFunc(elem, index, collection)
{
if (data.items[elem].id == searchItemId)
{
result.key = elem;
result.id = searchItemId;
}
}
}
function onLoaded(evt)
{
console.log( getIDs(rawData, "b") );
}
You can do:
const obj = {
someID: '16385421',
items: {
9836: {
id: 'a',
},
3648: {
id: 'b',
},
7738: {
id: 'c',
},
},
}
const getParentObjectByValue = (obj, value) => {
const key = Object.keys(obj.items).find((k) => obj.items[k].id === value)
return key ? { [key]: obj.items[key].id } : undefined
}
console.log(getParentObjectByValue(obj, 'b'))
console.log(getParentObjectByValue(obj, 'zz'))

Convert keys from key value pair to capital case using javaScript

I am trying to convert the keys in JSON to the capital case using Javascript. I am successful to some extent. However, it is not creating the arrays in the correct way. It is inserting numbers before every object inside an array.
Input:
{
"id": "123",
"retweetCheck": {
"result": "OK",
"checks": [
{
"cId": "123"
},
{
"cId": "456"
}
]
},
"tweetCheck": {
"result": "OK",
"cId": "345",
"check": "Fail"
}
}
Code to convert the keys to capital case:
var responseContent = context.getVariable("response.content") || "";
responseContent = JSON.parse(responseContent) || "";
transformedCapitalizedObj = keysToCapitalCase(responseContent);
var finalResponseObj = {
Data: transformedCapitalizedObj
};
context.setVariable("response.content", JSON.stringify(finalResponseObj));
The function
function objEntries(obj) {
const keys = Object.keys(obj);
const keyValuePairs = keys.map(key => {
const value = obj[key];
return [key, value];
});
return keyValuePairs;
}
function keysToCapitalCase(objToProcess) {
if (!objToProcess || typeof objToProcess !== "object") return null;
var finalObj = {};
objToProcess = objEntries(objToProcess);
objToProcess.forEach(function (entry) {
var key = entry[0];
var value = entry[1];
key = key.charAt(0).toUpperCase() + key.slice(1);
if (typeof value == "object" || (value instanceof Array)) {
value = keysToCapitalCase(value);
}
finalObj[key] = value;
});
return finalObj;
}
The output I am getting currently is:
{
"Data":{
"RetweetCheck":{
"Checks":{
"0":{
"CId":"123"
},
"1":{
"CId":"456"
}
},
"Result":"OK"
},
"Id":"123",
"TweetCheck":{
"CId":"345",
"Check":"Fail",
"Result":"OK"
}
}
}
But ideally, the output should look like this:
{
"Data": {
"Id": "123",
"RetweetCheck": {
"Result": "OK",
"Checks": [
{
"CId": "123"
},
{
"CId": "456"
}
]
},
"TweetCheck": {
"Result": "OK",
"CId": "345",
"Check": "Fail"
}
}
}
It is basically inserting a serial number before each object inside an array instead of []. How this can be rectified. Any help will really do wonders.
When you call your function keysToCapitalCase(), first check if you have an array (with ES6, you can do this using Array.isArray()), and if you do, you can map the objects / inner arrays within that array to the result of recursively calling your keysToCapitalize function. Otherwise, if you get a standard object that isn't an array, you can perform your standard object mapping:
const obj = { "id": "123", "retweetCheck": { "result": "OK", "checks": [{ "cId": "123" }, { "cId": "456" } ] }, "tweetCheck": { "result": "OK", "cId": "345", "check": "Fail" } };
function keysToCapitalCase(objToProcess) {
if (!objToProcess || typeof objToProcess !== "object") return null;
if(Array.isArray(objToProcess)) {
return objToProcess.map(obj => keysToCapitalCase(obj));
}
var finalObj = {};
objToProcess = Object.entries(objToProcess); // if you can support it, `Object.entries()` does what `objEntries` does
objToProcess.forEach(function(entry) {
var key = entry[0];
var value = entry[1];
key = key.charAt(0).toUpperCase() + key.slice(1);
if (typeof value == "object") {
value = keysToCapitalCase(value);
}
finalObj[key] = value;
});
return finalObj;
}
var finalResponseObj = {Data: keysToCapitalCase(obj)};
console.log(finalResponseObj);
I would probably write the above method in a similar way, but instead using some inbuilt functions to make it a little more concise, such as .map() and Object.fromEntries():
const obj = { "id": "123", "retweetCheck": { "result": "OK", "checks": [{ "cId": "123" }, { "cId": "456" } ] }, "tweetCheck": { "result": "OK", "cId": "345", "check": "Fail" } };
const cap = str => str.charAt(0).toUpperCase() + str.slice(1);
const keysToCapitalCase = (objToProcess) => {
if (Object(objToProcess) !== objToProcess) return null;
return Array.isArray(objToProcess)
? objToProcess.map(obj => keysToCapitalCase(obj))
: Object.fromEntries(Object.entries(objToProcess).map(([key, val]) => [
cap(key), Object(val) === val ? keysToCapitalCase(val) : val
]));
}
const finalResponseObj = {Data: keysToCapitalCase(obj)};
console.log(finalResponseObj);
As indicated by the {} brackets, instead of the wanted [] brackets you are creating an empty object and not an Array.
To create an Array just change your var finalObj = {}; to var finalObj = [];
with an Array finalObj[key] = value will no longer work, you will now have to use finalObj.push(value)

React JSON problem, iterate for a each key of a JSON Object

NOte: I have updated this question on 21/05/2021. pls answer to this question,
Data
{
"_id": "3fad6024-3226-451b-9e81-1c544aaaebf7",
"name": "ank retailer part 2",
"aboutUs": "part 2 updated",
"retailerLanguage": [
{
"languageID": "20b4772c-2470-4eaa-bc0c-61429700781cd",
"language": {
"name": "Koreandddd",
"__typename": "language"
}
},
{
"languageID": "8f04da56-0f53-4694-b6dc-0eb5a3aa2990",
"language": {
"name": "Mandarin",
"__typename": "language"
}
}
],
"termsAndConditions": "agreed"
}
I have tried this:
const tifOptionsES6 = Object.keys(d).map(key => {
return Edited "{key}" to {d[key]}
})
but unable to iterate for array key
Expected Output
Edited "name" to ank retailer part 2
Edited "aboutUs" to part 2 updated
Edited "retailerLanguage" to Koreandddd , Mandarin
Edited "termsAndConditions" to part 2 agreed
and also check for not null
const input = {"_id":"3fad6024-3226-451b-9e81-1c544aaaebf7","name":"ank retailer part 2","agents":[{"agentID":"89add463-7cb7-442a-b705-405e03f7e86a"},{"agentID":"1c98d888-6c43-463c-b7ed-79ea8736125f"}],"aboutUs":"part 2 updated","agentTitle":null,"retailerLanguage":[{"languageID":"8f04da56-0f53-4694-b6dc-0eb5a3aa2990"},{"languageID":"20b4772c-2470-4eaa-bc0c-61429700781c"},{"languageID":"3176fef7-9088-43c0-a8f3-47af51eb6e12"}],"retailerIndustries":[{"industryName":"Laundry"},{"industryName":"Aircon"}],"termsAndConditions":"not agreed"}
const mappings = {
agents: 'agentID',
retailerLanguage: 'languageID',
retailerIndustries: 'industryName'
}
const printInputKey = key => {
const item = input[key]
return typeof item === 'string'
? item
: item.map(x => x[mappings[key]])
}
const output = ['name', 'aboutUs', 'agents', 'retailerLanguage', 'retailerIndustries']
.map(key =>
`Edited "${key}" to ${printInputKey(key)}`
).join(' ')
console.log(output)
var data = {"_id":"3fad6024-3226-451b-9e81-1c544aaaebf7","name":"ank retailer part 2","agents":[{"agentID":"89add463-7cb7-442a-b705-405e03f7e86a"},{"agentID":"1c98d888-6c43-463c-b7ed-79ea8736125f"}],"aboutUs":"part 2 updated","agentTitle":null,"retailerLanguage":[{"languageID":"8f04da56-0f53-4694-b6dc-0eb5a3aa2990"},{"languageID":"20b4772c-2470-4eaa-bc0c-61429700781c"},{"languageID":"3176fef7-9088-43c0-a8f3-47af51eb6e12"}],"retailerIndustries":[{"industryName":"Laundry"},{"industryName":"Aircon"}],"termsAndConditions":"not agreed"};
var exclusions = ["termsAndConditions"];
function deflateJSON(data) {
if (typeof(data) == 'string')
return data;
else {
let result = Object.values(data).filter((x) => x != null);
for (var i = 0; i < result.length; i++) {
result[i] = deflateJSON(result[i]);
}
return result.join(",");
}
}
function processData(data, exclusions) {
let p = [];
for (const [key, value] of Object.entries(d)) {
(value != null && !exclusions.includes(key)) && p.push(`Edited "${key}" to ${ deflateJSON(value) }`)
}
return p.join("\n");
}
console.log(processData(data,exclusions));

How to change the value of an Array object in Javascript

I have an array object call listOfObjects.
[{"name":"A", "data":"[{"value1":"1","value2":"2"}]"},
{"name":"B", "data":"[{"value1":"1","value2":"2"}]"}]
What I want to do is insert an object into the array where the array is empty.If the array is not empty then do a check on the item inside. If item already exist, do update on the item, else add it to the array. Below is my code
var searchName= "A";
if (listOfObjects.length > 0) {
for (var i = 0; i < listOfObjects.length; i++) {
if (listOfObjects[i].name == searchName) {
listOfObjects[i].data = data;
break;
} else {
insert = {
'name': searchName,
'data': data
};
listOfObjects.push(insert);
}
}
} else {
insert = {
'name': searchName,
'data': data
};
listOfObjects.push(insert);
}
When I run it, even though A already exist, it update the existing item but also add one more time to the listOfObjects. Is there anyway that can achieve what I want? Thanks..
The problem is you're inserting into the array inside your for loop looking for a match. Instead, remember whether you've seen a match and insert after the loop if you haven't. There's also no reason for the length check and no reason to repeat your logic for inserting:
var searchName= "A";
var found = false;
for (var i = 0; !found && i < listOfObjects.length; i++) {
if (listOfObjects[i].name == searchName) {
listOfObjects[i].data = data;
found = true;
}
}
if (!found) {
listOfObjects.push({
'name': searchName,
'data': data
});
}
Note that you can use Array#find (which can be polyfilled for old browsers) to find the entry rather than a for loop if you like:
var searchName= "A";
var entry = listOfObjects.find(function(entry) {
return entry.name == searchName;
});
if (entry) {
entry.data = data;
} else {
listOfObjects.push({
'name': searchName,
'data': data
});
}
First of all change this
[{"name":"A", "data":"[{"value1":"1","value2":"2"}]"},
{"name":"B", "data":"[{"value1":"1","value2":"2"}]"}]
by
[{"name":"A", "data":[{"value1":1,"value2":2}]},
{"name":"B", "data":[{"value1":"1","value2":"2"}]}];
because your list will throw Uncaught SyntaxError: Unexpected identifier
Write another simple function to get the item listOfObjects[i] with selected searchName. Here 'getSearchObject()' function checks the existance of searchName and then add or updates array.
addOrRemoveItem() {
let listOfObjects = [
{ "name": "A", "data": "[{'value1':'1','value2':'2'}]" },
{ "name": "B", "data": "[{'value1':'1','value2':'2'}]" }
],
data = '[{"value1":"1","value2":"2"}]';
var searchName = "C";
if (listOfObjects.length > 0) {
let searchObj = this.getSearchObject(listOfObjects, searchName);
if (searchObj) {
searchObj.data = data;
} else {
let insert = {
"name": searchName,
"data": data
}
listOfObjects.push(insert);
}
} else {
let insert = {
"name": searchName,
"data": data
}
listOfObjects.push(insert);
}
}
getSearchObject(objArr, searchKey) {
var obj = null;
for (let i = 0; i < objArr.length; i++) {
if (objArr[i].name === searchKey) {
obj = objArr[i];
}
}
return obj;
}
A generic solution that recognizes older JS engines (filter instead of find) but does always assume getting passed a list of unique items could be implemented like this ...
function updateList(itemList, item) { // - always assume a list of unique items.
var
itemName = item.name,
listItem = itemList.filter(function (elm) { // - assume `filter`, not find`.
return (elm.name === itemName); // - find/get existing list item by name.
})[0];
if (listItem) {
listItem.data = item.data;
} else {
itemList.push(item)
}
}
var list = [
{ "name": "A", "data": [ { "value1": "A1", "value2": "A2" }] },
{ "name": "B", "data": [ { "value1": "B1", "value2": "B2" }] },
{ "name": "C", "data": [ { "value1": "C1", "value2": "C2" }] }
];
console.log('list : ', list);
updateList(list, { "name": "D", "data": [ { "value1": "D1", "value2": "D2" }] });
updateList(list, { "name": "B", "data": [ { "value1": "b_1", "value2": "b_2", "value3": "b_3" }] });
updateList(list, { "name": "C", "data": [ { "value3": "C3" }] });
console.log('list : ', list);
.as-console-wrapper { max-height: 100%!important; top: 0; }

How do I display my RSS feed horizontally?

I want to display my custom RSS feed as a horizontal list. I am using a responsive template and embedding my feeds into that template. I believe that my JavaScript is not separating each RSS post into a separate list item like I thought it would.
(function($) {
"use strict";
var RSS = function(target, url, options, callback) {
this.target = target
this.url = url
this.html = []
this.effectQueue = []
this.options = $.extend({
ssl: false,
limit: null,
key: null,
layoutTemplate: '<ul style="display:inline-block;">{entries}</ul>',
entryTemplate: '<li><div class="title">{title}</div><br /><author>{author}</author><img src="{teaserImageUrl}"></img><date>{date}</date><br />{shortBodyPlain}</li>',
tokens: {
},
outputMode: 'json',
dateFormat: 'MMM Do, YYYY',
effect: 'show',
offsetStart: false,
offsetEnd: false,
error: function() {
console.log("jQuery RSS: url doesn't link to RSS-Feed");
},
onData: function(){},
success: function(){}
}, options || {})
this.callback = callback || this.options.success
}
RSS.htmlTags = ["doctype", "html", "head", "title", "base", "link", "meta", "style", "script", "noscript", "body", "article", "nav", "aside", "section", "header", "footer", "h1-h6", "hgroup", "address", "p", "hr", "pre", "blockquote", "ol", "ul", "li", "dl", "dt", "dd", "figure", "figcaption", "div", "table", "caption", "thead", "tbody", "tfoot", "tr", "th", "td", "col", "colgroup", "form", "fieldset", "legend", "label", "input", "button", "select", "datalist", "optgroup", "option", "textarea", "keygen", "output", "progress", "meter", "details", "summary", "command", "menu", "del", "ins", "img", "iframe", "embed", "object", "param", "video", "audio", "source", "canvas", "track", "map", "area", "a", "em", "strong", "i", "b", "u", "s", "small", "abbr", "q", "cite", "dfn", "sub", "sup", "time", "code", "kbd", "samp", "var", "mark", "bdi", "bdo", "ruby", "rt", "rp", "span", "br", "wbr"]
RSS.prototype.load = function(callback) {
var apiProtocol = "http" + (this.options.ssl ? "s" : "")
, apiHost = apiProtocol + "://ajax.googleapis.com/ajax/services/feed/load"
, apiUrl = apiHost + "?v=1.0&output=" + this.options.outputMode + "&callback=?&q=" + encodeURIComponent(this.url)
// set limit to offsetEnd if offset has been set
if(this.options.offsetStart && this.options.offsetEnd) this.options.limit = this.options.offsetEnd;
if (this.options.limit != null) apiUrl += "&num=" + this.options.limit;
if (this.options.key != null) apiUrl += "&key=" + this.options.key;
$.getJSON(apiUrl, callback)
}
RSS.prototype.render = function() {
var self = this
this.load(function(data) {
try {
self.feed = data.responseData.feed
self.entries = data.responseData.feed.entries
} catch(e) {
self.entries = []
self.feed = null
return self.options.error.call(self)
}
var html = self.generateHTMLForEntries()
self.target.append(html.layout)
if (html.entries.length !== 0) {
$.isFunction(self.options.onData) && self.options.onData.call(self);
self.appendEntriesAndApplyEffects($("entries", html.layout), html.entries);
}
if (self.effectQueue.length > 0) {
self.executeEffectQueue(self.callback)
} else {
$.isFunction(self.callback) && self.callback.call(self);
}
})
}
RSS.prototype.appendEntriesAndApplyEffects = function(target, entries) {
var self = this
$.each(entries, function(idx, entry) {
var $html = self.wrapContent(entry)
if(self.options.effect === 'show') {
target.before($html)
} else {
$html.css({ display: 'none' })
target.before($html)
self.applyEffect($html, self.options.effect)
}
})
target.remove()
}
RSS.prototype.generateHTMLForEntries = function() {
var self = this
, result = {
entries: [],
layout: null
}
$(this.entries).each(function() {
var entry = this,
offsetStart = self.options.offsetStart,
offsetEnd = self.options.offsetEnd;
// offset required
if(offsetStart && offsetEnd) {
if(index >= offsetStart && index <= offsetEnd) {
if(self.isRelevant(entry, result.entries)) {
var evaluatedString = self.evaluateStringForEntry(self.options.entryTemplate, entry)
result.entries.push(evaluatedString)
}
}
}else{
// no offset
if(self.isRelevant(entry, result.entries)) {
var evaluatedString = self.evaluateStringForEntry(self.options.entryTemplate, entry)
result.entries.push(evaluatedString)
}
}
})
if(!!this.options.entryTemplate) {
// we have an entryTemplate
result.layout = this.wrapContent(this.options.layoutTemplate.replace("{entries}", "<entries></entries>"))
} else {
// no entryTemplate available
result.layout = this.wrapContent("<div><entries></entries></div>")
}
return result
}
RSS.prototype.wrapContent = function(content) {
if($.trim(content).indexOf('<') !== 0) {
// the content has no html => create a surrounding div
return $("<div>" + content + "</div>")
} else {
// the content has html => don't touch it
return $(content)
}
}
RSS.prototype.applyEffect = function($element, effect, callback) {
var self = this
switch(effect) {
case 'slide':
$element.slideDown('slow', callback)
break
case 'slideFast':
$element.slideDown(callback)
break
case 'slideSynced':
self.effectQueue.push({ element: $element, effect: 'slide' })
break
case 'slideFastSynced':
self.effectQueue.push({ element: $element, effect: 'slideFast' })
break
}
}
RSS.prototype.executeEffectQueue = function(callback) {
var self = this
this.effectQueue.reverse()
var executeEffectQueueItem = function() {
var item = self.effectQueue.pop()
if(item) {
self.applyEffect(item.element, item.effect, executeEffectQueueItem)
} else {
callback && callback()
}
}
executeEffectQueueItem()
}
RSS.prototype.evaluateStringForEntry = function(string, entry) {
var result = string
, self = this
$(string.match(/(\{.*?\})/g)).each(function() {
var token = this.toString()
result = result.replace(token, self.getValueForToken(token, entry))
})
return result
}
RSS.prototype.isRelevant = function(entry, entries) {
var tokenMap = this.getTokenMap(entry)
if(this.options.filter) {
if(this.options.filterLimit && (this.options.filterLimit == entries.length)) {
return false
} else {
return this.options.filter(entry, tokenMap)
}
} else {
return true
}
}
RSS.prototype.getTokenMap = function(entry) {
if (!this.feedTokens) {
var feed = JSON.parse(JSON.stringify(this.feed))
delete feed.entries
this.feedTokens = feed
}
return $.extend({
feed: this.feedTokens,
url: entry.link,
author: entry.author,
date: moment(entry.publishedDate).format(this.options.dateFormat),
title: entry.title,
body: entry.content,
shortBody: entry.contentSnippet,
bodyPlain: (function(entry) {
var result = entry.content
.replace(/<script[\\r\\\s\S]*<\/script>/mgi, '')
.replace(/<\/?[^>]+>/gi, '')
for(var i = 0; i < RSS.htmlTags.length; i++) {
result = result.replace(new RegExp('<' + RSS.htmlTags[i], 'gi'), '')
}
return result
})(entry),
shortBodyPlain: entry.contentSnippet.replace(/<\/?[^>]+>/gi, ''),
//shortBodyPlain: entry.contentSnippet.replace("-- Delivered by Feed43 service", ""),
shortBodyPlain: entry.contentSnippet.replace("369gopee", "<author>").replace("321gopee", "</author><br />"),
index: $.inArray(entry, this.entries),
totalEntries: this.entries.length,
teaserImage: (function(entry){
try { return entry.content.match(/(<img.*?>)/gi)[0] }
catch(e) { return "" }
})(entry),
teaserImageUrl: (function(entry) {
try { return entry.content.match(/(<img.*?>)/gi)[0].match(/src="(.*?)"/)[1] }
catch(e) { return "" }
})(entry)
}, this.options.tokens)
}
RSS.prototype.getValueForToken = function(_token, entry) {
var tokenMap = this.getTokenMap(entry)
, token = _token.replace(/[\{\}]/g, '')
, result = tokenMap[token]
if(typeof result != 'undefined')
return ((typeof result == 'function') ? result(entry, tokenMap) : result)
else
throw new Error('Unknown token: ' + _token)
}
$.fn.rss = function(url, options, callback) {
new RSS(this, url, options, callback).render()
return this; //implement chaining
}
})(jQuery)
When I view the page source, there is not dynamically created html. How would I display these list items inline?
The feeds appear in HTML as follows:
<script>
jQuery(function($) {
$("#rss-feeds").rss("http://www.feed43.com/channelfireball.xml", {
limit: 15
})
</script>
<div style="border:none;width:100%;height:auto;overflow-y:scroll;
overflow-x:scroll;">
<div class="span2 item">
<div class="item-wrap">
<div class="post_results" id="rss-feeds"></div>
</div>
</div>
</div>

Categories

Resources