Adding nodes to bootstrap treeview dynamically - json

I currently have a huge JSON file (over 15k lines, size might increase) with which I want to construct a bootstrap-treeview. Adding all the nodes would make loading of page really slow, so I plan to create a service to fetch JSON of selected nodes and populate the treeview accordingly. This is what I have right now.
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Tree View</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<link href="./TreeView_files/bootstrap-treeview.css" rel="stylesheet">
</head>
<body>
<div class="container">
<h1>Bootstrap Tree View - DOM Tree</h1>
<br/>
<div class="row">
<div class="col-sm-12">
<label for="treeview"></label>
<div id="treeview"/>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="./TreeView_files/bootstrap-treeview.js"></script>
<script type="text/javascript">
function buildDomTree() {
var tree = [
{
text: "Parent 1",
nodes: [
{
text: "Child 1",
nodes: [
{
text: "Grandchild 1"
},
{
text: "Grandchild 2"
}
]
},
{
text: "Child 2"
}
]
},
{
text: "Parent 2"
},
{
text: "Parent 3"
},
{
text: "Parent 4"
},
{
text: "Parent 5"
}
];
return tree;
}
$(function() {
var options = {
bootstrap2: false,
showTags: true,
levels: 5,
data: buildDomTree()
};
$('#treeview').treeview(options);
});
</script>
</body>
Treeview can go 4 levels deep, and I want to fetch next level JSON each time a node is clicked. So, if I click on "Parent 5", it should pop out sub nodes.
I have no clue how to add nodes dynamically. Any help would be really appreciated.

Answer on request: I have found a way to do it, although, it is a tad inefficient. What I've done is, I keep a state of all expanded nodes, and when I click on a node to expand it, I make an HTTP request, add the new nodes to the old one, redraw the entire tree and re-expand all the previously expanded nodes. I know this is inefficient, but it is the only way I could find without going into the nitty-gritty and essentially recreating the entire tree myself (which is just a glorified recursion application).
Here's the code I ran with when I posted the question. There is obviously room for improvement.
var expandedNodes = [];
var tree = [];
$(function()
{
$.post("http://localhost:8000/getLevel1", function( data )
{
var JSObject = JSON.parse(data);
for (j in JSObject)
tree.push(JSObject[j]);
createTree();
});
});
function createTree(){
var options = {
bootstrap2: false,
showTags: true,
levels: 0,
data: tree,
expandIcon: 'fa fa-chevron-right',
collapseIcon: 'fa fa-chevron-down',
onNodeExpanded: nodeExpand,
onNodeCollapsed: nodeCollapse,
onNodeSelected: nodeSelect,
onNodeUnselected: nodeUnselect
}
$('#treeview').treeview(options);
for (node in expandedNodes)
$('#treeview').treeview('expandNode', [ expandedNodes[node], { levels: 0, silent: true } ]);
$('#treeview').treeview('expandNode', 0, { silent: true } );
};
function nodeExpand(event, data)
{
expandedNodes.push(data.nodeId);
var requestObject = []
requestObject.push(data.text);
var parent, dummy = data;
while ((parent = $('#treeview').treeview('getParent', dummy.nodeId))["nodeId"] != undefined)
{
requestObject.push(parent.text);
dummy = parent;
}
$.post("http://localhost:8000/getNode?param=" + JSON.stringify(requestObject), function(retVal)
{
var JSObject = JSON.parse(retVal);
var node = findNode(requestObject);
node.nodes = JSObject;
createTree();
});
}
function nodeCollapse(event, data)
{
var index = expandedNodes.indexOf(data.nodeId);
if (index > -1)
expandedNodes.splice(index, 1);
}
function nodeSelect(event, data)
{
if (data.state.expanded == true)
$('#treeview').treeview('collapseNode', data.nodeId);
else
$('#treeview').treeview('expandNode', data.nodeId);
//$('#treeview').treeview('unselectNode', [ data.nodeId, { silent: true } ]);
}
function nodeUnselect(event, data)
{
}
function findNode(array)
{
var searchIn = tree; //array
var lastFound = tree;
for (var i = array.length - 1; i >= 0; i--)
{
var obj = searchInObject(searchIn, array[i]);
searchIn = obj.nodes;
lastFound = obj;
}
return lastFound;
}
function searchInObject(objectArray, string)
{
for (var index in objectArray)
if (objectArray[index].text == string)
return objectArray[index];
}
$(document).ready(function () {
var trigger = $('.hamburger'),
overlay = $('.overlay'),
isClosed = false;
hamburger_cross();
$('#wrapper').toggleClass('toggled');
trigger.click(function () {
hamburger_cross();
});
function hamburger_cross() {
if (isClosed == true) {
overlay.hide();
trigger.removeClass('is-open');
trigger.addClass('is-closed');
isClosed = false;
$('#open_arrow').removeClass('fa-chevron-circle-left').addClass('fa-chevron-circle-right');
} else {
overlay.show();
trigger.removeClass('is-closed');
trigger.addClass('is-open');
isClosed = true;
$('#open_arrow').removeClass('fa-chevron-circle-right').addClass('fa-chevron-circle-left');
}
}
$('[data-toggle="offcanvas"]').click(function () {
$('#wrapper').toggleClass('toggled');
});
});
Point of interest would be nodeExpand and createTree methods.

Related

Chrome extension web inspector

I want to write a chrome extension where it is possible to mark features on a website and save it in a table, for this, I want to use the Chrome web inspector.
Unfortunately, I am new to this area (chrome plugins) and therefore I am looking for help (links, tutorials, related work etc.) to use the web inspector in my own extension.
Simple example on this website https://ieeexplore.ieee.org/document/1005630.
My idea is to mark for example the date of publication, and the plugin write the complete div to a table.
actually, I found a simple solution.
Sample
http://g.recordit.co/5CCFjXpe8J.gif
It's only a small part of my tool to keep it simple.
The main idea comes from Google Chrome Extension: highlight the div that the mouse is hovering over
'iframe' is the injected sidebar
marker.js contains the script to mark divs
manifest.json
{
"name": "Feature extractor",
"version": "1.0",
"description": "Feature extractor from website",
"permissions": ["activeTab", "declarativeContent", "storage", "contextMenus", "<all_urls>", "tabs"],
"browser_action": {},
"web_accessible_resources": ["iframe.html","iframe.js"],
"background": {
"scripts": ["background.js"],
"persistent": false
},
"content_scripts": [
{
"matches": [
"http://*/*",
"https://*/*"
],
"css": [
"marker.css"
],
"js": [
"js/jquery-1.8.3.min.js",
"marker.js"
]
}
],
"manifest_version": 2
}
background.js
'use strict';
chrome.runtime.onInstalled.addListener(function() {
chrome.declarativeContent.onPageChanged.removeRules(undefined, function() {
chrome.declarativeContent.onPageChanged.addRules([{
conditions: [new chrome.declarativeContent.PageStateMatcher({
pageUrl: {hostEquals: 'developer.chrome.com'},
})],
actions: [new chrome.declarativeContent.ShowPageAction()]
}]);
});
});
// sidebar
chrome.browserAction.onClicked.addListener(function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id,"toggle");
})
});
// message passing
chrome.runtime.onMessage.addListener(function(request, sender, callback) {
console.log(request);
callback({'request':request});
});
// context menu
var labels = ['author','date','abstract']
for(var label in labels) {
console.log(labels[label])
chrome.contextMenus.create({id: labels[label], "title": labels[label], "contexts":['all']});
}
chrome.contextMenus.onClicked.addListener(function(info, tab) {
if (info.menuItemId == labels[0]) {
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
chrome.tabs.sendMessage(tabs[0].id,labels[0]);
})
}
});
iframe.html
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/jquery.mobile-1.2.1.min.css" />
<script src="js/jquery-1.8.3.min.js"></script>
<script src="js/jquery.mobile-1.2.1.min.js"></script>
<script src="iframe.js"></script>
</head>
<body>
<button id="send">
send
</button>
<div id="responses">
</div>
</body>
</html>
I need the jQuery.fn.. script to identify the selected div Get unique selector of element in Jquery
iframe.js
// unique selector
jQuery.fn.extend({
getPath: function () {
var path, node = this;
while (node.length) {
var realNode = node[0], name = realNode.localName;
if (!name) break;
name = name.toLowerCase();
var parent = node.parent();
var sameTagSiblings = parent.children(name);
if (sameTagSiblings.length > 1) {
var allSiblings = parent.children();
var index = allSiblings.index(realNode) + 1;
if (index > 1) {
name += ':nth-child(' + index + ')';
}
}
path = name + (path ? '>' + path : '');
node = parent;
}
return path;
}
});
window.addEventListener('DOMContentLoaded', function () {
var callback = function (data) {
$("#responses").append("<div>" + data + "</div>");
};
var send = function () {
chrome.runtime.sendMessage(Date(), callback);
}
chrome.runtime.onMessage.addListener(function(msg, data){
if (msg.command == "append-author") {
$("#responses").append("<div>" + msg.el + "</div>")
}
})
document.getElementById('send').addEventListener('click', send);
});
Google Chrome Extension: highlight the div that the mouse is hovering over
marker.js
// Unique ID for the className.
var MOUSE_VISITED_CLASSNAME = 'crx_mouse_visited';
var MOUSE_MARKED_CLASSNAME = 'crx_mouse_marked';
// Previous dom, that we want to track, so we can remove the previous styling.
var prevDOM = null;
// Mouse listener for any move event on the current document.
document.addEventListener('mousemove', function (e) {
let srcElement = e.srcElement;
// Lets check if our underlying element is a IMG.
if (prevDOM != srcElement && srcElement.nodeName == 'DIV' ) {
// For NPE checking, we check safely. We need to remove the class name
// Since we will be styling the new one after.
if (prevDOM != null) {
prevDOM.classList.remove(MOUSE_VISITED_CLASSNAME);
}
// Add a visited class name to the element. So we can style it.
srcElement.classList.add(MOUSE_VISITED_CLASSNAME);
// The current element is now the previous. So we can remove the class
// during the next ieration.
prevDOM = srcElement;
// console.info(srcElement.currentSrc);
// console.dir(srcElement);
}
}, false);
var iframe = document.createElement('iframe');
iframe.style.background = "green";
iframe.id = "comm-test-container";
iframe.style.height = "100%";
iframe.style.width = "0px";
iframe.style.position = "fixed";
iframe.style.top = "0px";
iframe.style.right = "0px";
iframe.style.zIndex = "9000000000000000000";
iframe.frameBorder = "none";
iframe.src = chrome.extension.getURL("iframe.html")
document.body.appendChild(iframe);
function toggle(){
if(iframe.style.width == "0px") {
iframe.style.width="400px";
} else {
iframe.style.width="0px";
}
}
chrome.runtime.onMessage.addListener(function(msg, sender){
if(msg == "toggle"){
toggle();
}
if(msg == "author") {
prevDOM.classList.add(MOUSE_MARKED_CLASSNAME);
chrome.runtime.sendMessage({command:"append-author",el:prevDOM.innerHTML,selector:$(prevDOM).getPath()}, function(response) {});
}
})
// find unique selector
jQuery.fn.extend({
getPath: function () {
var path, node = this;
while (node.length) {
var realNode = node[0], name = realNode.localName;
if (!name) break;
name = name.toLowerCase();
var parent = node.parent();
var sameTagSiblings = parent.children(name);
if (sameTagSiblings.length > 1) {
var allSiblings = parent.children();
var index = allSiblings.index(realNode) + 1;
if (index > 1) {
name += ':nth-child(' + index + ')';
}
}
path = name + (path ? '>' + path : '');
node = parent;
}
return path;
}
});
marker.css
.crx_mouse_visited {
background-clip: #bcd5eb!important;
outline: 1px dashed #e9af6e!important;
z-index : 0!important;
}
.crx_mouse_marked {
background-clip: #bcd5eb!important;
outline: 5px solid #e9af6e!important;
z-index : 0!important;
}

Quill strips out simple html when dangerouslyPasteHTML into editor

<style>
#editor-container {
height: 375px;
}
.link {
color:blue;
}
</style>
<div id="editor-container">
This is a test
</div>
<script type="text/javascript">
var quill = new Quill('#editor-container', {
modules: {
toolbar: [
[{ header: [1, 2, false] }],
['bold', 'italic', 'underline'],
['image', 'code-block']
]
},
placeholder: 'Compose an epic...',
theme: 'bubble' // or 'bubble'
});
quill.clipboard.dangerouslyPasteHTML(5, "<span class=\"link\" data-test=\"test\">testing</span>", "silent");
</script>
MVCE - https://codepen.io/anon/pen/QMQMee
The HTML get stripped out despite being pretty harmless (this will be handled better later).
My current plan, due to the way Quill does not allow pasted html, is (As part of a click action on the mentioned person's name):
$("#tag-selectable-users-list li").on("click",
function() {
var $this = $(this);
var startIndex = $this.data("data-start-index");
var userName = $this.data("data-user-name");
var userId = $this.data("data-user-id");
var taggedUserIds = $("#hiddenTaggedUsers");
taggedUserIds.val((taggedUserIds.val()||"") + ";" + userId);
var delta = [];
if (startIndex > 0) {
//retain up to the tag start
delta.push({ retain: parseInt(startIndex) });
}
//delete the junk
delta.push({ delete: tagStatus.Total.length });
//insert the new characters
delta.push({
insert: "##" + userName,
attributes: {
color: "blue",
underline: "true"
}
});
//insert a blank space to end the span
delta.push({ insert: " " });
quill.updateContents(delta,
'api');
});
}

Knockout observable field in array to indicate order of items

I have a html view that's connected to Knockout viewmodel, and displays a list of items.
Each item in the list contains a textual name field, and a numeric order field.
A user can perform a "drag and drop" action to items in the UL list.
The "drag and drop" event changes the order of the items as follows:
<div id="wrapper">
<ul data-bind="foreach:Items">
<li draggable="true"
ondragover="event.preventDefault();"
data-bind="event:{dragstart:$root.dragItem,drop:$root.dropItem}">
<label data-bind="text:name"></label>
<label data-bind="text:orderNo"></label>
<input type="text" data-bind="value:name" />
</li>
</ul>
<script type="text/javascript">
var list = [{ name: 'Red', orderNo: 0 }
, { name: 'Green', orderNo: 1 }
, { name: 'Blue', orderNo: 2 }];
function viewmodel() {
var self = this;
self.Items = ko.mapping.fromJS(list);
self.ItemToDrag = ko.observable();
self.dragItem = function (item, event) {
self.ItemToDrag(item);
return true;
}
self.dropItem = function (item, event) {
event.preventDefault();
var up = self.ItemToDrag().orderNo() > item.orderNo();
self.ItemToDrag().orderNo(up ? item.orderNo() - 0.5 : item.orderNo() + 0.5);
//order this list
self.Items.sort(function (left, right) {
return left.orderNo() == right.orderNo() ? 0 : (left.orderNo() < right.orderNo() ? -1 : 1);
});
//set integer number
for (var i = 0; i < self.Items().length; i++) {
self.Items()[i].orderNo(i);
}
}
}
var vm;
$(document).ready(function () {
vm = new viewmodel();
ko.applyBindings(vm, $("#wrapper")[0]);
});
My question is, if it is possible with Knockout to change the contents of the order field automatically when the items of the list change their order through the UI.
Something like
<ul data-bind="foreach:Items,orderKey:orderNo"></ul>
Where orderKey indicates the order of the items, and which field to update in case of order change.
I'm not sure this is exactly what you need. This is custom binding, that sorts an array from foreach binding before:
ko.bindingHandlers.foreach["after"] = ["orderKey"];
ko.bindingHandlers.orderKey = {
update: function (el, valueAccessor, allBindingsAccessor, viewModel) {
var key = ko.unwrap(valueAccessor());
var allBindings = allBindingsAccessor();
if("foreach" in allBindings) {
var array = ko.unwrap(allBindings.foreach);
array.sort(function(a, b) { return a[key] > b[key]; });
allBindings.foreach = array;
}
}
};
// The model
var model = { Items: ko.observableArray([{text: 3}, {text: 1}, {text: 2}]) };
// Apply
ko.applyBindings(model);
// This simulate changes in observableArray
setTimeout(function() { model.Items.push({text: 0}) }, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.0/knockout-min.js"></script>
<ul data-bind="foreach: Items, orderKey: 'text'">
<li data-bind="text: text"></li>
</ul>
No, there is no specific binding for that use case. In knockout, however, it is simple to write a custom binding. See the documentation. In the company I'm working for, we're using a knockout-based framework (developed by us) with tons of custom bindings, some of them really complex.
I just started to create such a binding for your use case. But I realized, it won't fit the purpose unless you have dozens of such lists.
What you can do, however, is to sort put the actual sorting into a knockout computed and just do the updating of the sort index in your drop function. See example below and don't hesitate to ask if something is not clear.
var list = [{ name: 'Red', orderNo: 0 }
, { name: 'Green', orderNo: 1 }
, { name: 'Blue', orderNo: 2 }];
function viewmodel() {
var self = this;
self._items = ko.mapping.fromJS(list);
self.Items = ko.pureComputed(function () {
return self._items().sort(function (a, b) {
return a.orderNo() < b.orderNo() ? -1 : 1;
});
});
self.ItemToDrag = ko.observable();
self.dragItem = function (item, event) {
self.ItemToDrag(item);
return true;
}
self.dropItem = function (item, event) {
event.preventDefault();
var up = self.ItemToDrag().orderNo() > item.orderNo();
self.ItemToDrag().orderNo(up ? item.orderNo() - 0.5 : item.orderNo() + 0.5);
}
}
var vm;
$(document).ready(function () {
vm = new viewmodel();
ko.applyBindings(vm, $("#wrapper")[0]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout.mapping/2.4.1/knockout.mapping.min.js"></script>
<div id="wrapper">
<ul data-bind="foreach:Items">
<li draggable="true"
ondragover="event.preventDefault();"
data-bind="event:{dragstart:$root.dragItem,drop:$root.dropItem}">
<label data-bind="text:name"></label>
<label data-bind="text:orderNo"></label>
<input type="text" data-bind="value:name" />
</li>
</ul>

Polymer inheritance, parent methods undefined

I am trying to understand how Polymer inheritance works.
I have a parent element fow-filter that contains general filter methods.
<link rel="import" href="../../bower_components/polymer/polymer.html">
<polymer-element name="fow-filter" attributes="">
<template>
<style>
:host {
display: block;
}
</style>
</template>
<script>
(function () {
Polymer("fow-filter",{
created: function(){
console.log("created");
},
ready: function(){
console.log("ready");
},
filterOnRange: function(cardList, key, min, max){
min = parseInt(min);
max = parseInt(max);
if(cardList){
return cardList.filter(
function(card){
return (card[key] >= min) && (card[key] <= max);
}
);
} else {
return [];
}
},
filterOnText: function(cardList, key, filterString, remaining){
if(filterString === "" || filterString === "radio_all"){
return cardList;
}
else if(cardList){
var self = this;
return cardList.filter(
function(card){
//console.log(card);
if( self.strictMatch(card[key], filterString) ){
return true;
} else if(remaining){
remaining.push(card);
}
return false;
}
);
} else {
return [];
}
},
strictMatch: function(text, textToSearch){
if(text && textToSearch){
return ( text.toUpperCase().indexOf(textToSearch.toUpperCase()) > -1 );
} else{
return false;
}
},
fuzzyMatch: function(text, textToSearch){
var search = textToSearch.toUpperCase();
var text = text.toUpperCase();
var j = -1; // remembers position of last found character
// consider each search character one at a time
for (var i = 0; i < search.length; i++) {
var l = search[i];
if (l == ' ') {
continue; // ignore spaces
}
j = text.indexOf(l, j+1); // search for character & update position
if (j == -1) {
return false; // if it's not found, exclude this item
}
}
return true;
}
});
})();
</script>
</polymer-element>
And I have another elements that extends it:
fow-card-filter
<link rel="import" href="../../bower_components/polymer/polymer.html">
<link rel="import" href="../../elements/elements.html">
<polymer-element name="fow-card-filter" attributes="filteredCards cards nameFilter descriptionFilter attributeFilter typeFilter rarityFilter expansionFilter minCost maxCost minCost maxCost minATK maxATK minDEF maxDEF" extends="fow-filter">
<template>
<style>
:host {
display: block;
}
</style>
</template>
<script>
Polymer("fow-card-filter",{
observe: {
"cards nameFilter descriptionFilter attributeFilter typeFilter" : "updateFilteredCards",
"rarityFilter expansionFilter minCost maxCost" : "updateFilteredCards",
"minCost maxCost minATK maxATK minDEF maxDEF" : "updateFilteredCards"
},
created: function (){
this.resetFilters();
},
resetFilters: function(){
this.nameFilter = "";
this.descriptionFilter = "";
this.attributeFilter = "radio_all";
this.typeFilter = "radio_all";
this.rarityFilter = "radio_all";
this.expansionFilter = "radio_all";
this.minCost = "0";
this.maxCost = "20";
this.minATK = "0";
this.maxATK = "10000";
this.minDEF = "0";
this.maxDEF = "10000";
},
updateFilteredCards: function(){
this.filteredCards = this.filterOnText(this.cards, "Name", this.nameFilter);
if(this.descriptionFilter){
this.filteredCards = this.filterOnText(this.filteredCards, "Cardtext", this.descriptionFilter);
}
if(this.attributeFilter){
this.filteredCards = this.filterOnText(this.filteredCards, "Attribute", this.attributeFilter);
}
if(this.rarityFilter){
this.filteredCards = this.filterOnText(this.filteredCards, "Rarity", this.rarityFilter);
}
if(this.expansionFilter){
this.filteredCards = this.filterOnText(this.filteredCards, "Expansion", this.expansionFilter);
}
if(this.typeFilter === "spell"){
//optimize filter
var remainingCards = [];
var spellCards = this.filterOnText(this.filteredCards, "Type", this.typeFilter, remainingCards);
var remainingCards2 = [];
var chantCards = this.filterOnText(remainingCards, "Type", "Chant", remainingCards2);
var istantCards = this.filterOnText(remainingCards2, "Type", "Instant");
this.filteredCards = spellCards.concat(chantCards,istantCards);
} else {
this.filteredCards = this.filterOnText(this.filteredCards, "Type", this.typeFilter);
}
this.filteredCards = this.filterOnRange(this.filteredCards, "Total Cost", this.minCost, this.maxCost);
if((this.typeFilter !== 'spell') && (this.typeFilter !== 'addition')){
this.filteredCards = this.filterOnRange(this.filteredCards, "Total Cost", this.minCost, this.maxCost);
this.filteredCards = this.filterOnRange(this.filteredCards, "ATK", this.minATK, this.maxATK);
this.filteredCards = this.filterOnRange(this.filteredCards, "DEF", this.minDEF, this.maxDEF);
}
}
});
</script>
</polymer-element>
However it seems that my fow-card-filter element does not see its parent methods, every time I call them i get a:
Exception caught during observer callback: TypeError: undefined is not a function
e.g.
this.filteredCards = this.filterOnText(this.cards, "Name", this.nameFilter);
Am I doing something wrong or is there something I am missing about Polymer inheritance?
EDIT:
I don't know why the created and ready methods are called in the parent fow-filter element without first entering the fow-card-filter element ready method.
Calling this.super() in fow-card-filter gives me:
called super() on a method not installed declaratively (has no .nom property)
Eventually I found out that importing the whole elements.html file was wrong.
<link rel="import" href="../../elements/elements.html">
Replacing it with only the parent element solved my problem:
<link rel="import" href="../../elements/fow-filter/fow-filter.html">

Polymer - reload core-list data

I wanted reload a core-list element to show new data, but it´s not refreshing.
I re-call the JS function thats generate the data but doesn t work... and reload like a 'normal' div doesn t work either! The list only shows the new data if i reload the entire page...
function values(sender, textomsg, datacriacao, senderfoto){
var sender2 = sender.split(",");
var textomsg2 = textomsg.split(",");
var datacriacao2 = datacriacao.split(",");
var senderfoto2 = senderfoto.split(",");
var namegen = {
generateString: function (inLength) {
var s = '';
for (var i = 0; i < inLength; i++) {
s += String.fromCharCode(Math.floor(Math.random() * 26) + 97);
}
return s;
},
generateName: function (inMin, inMax) {
return this.generateString(Math.floor(Math.random() * (inMax - inMin + 1) + inMin));
}
};
Polymer('list-test', {
count: sender.length,
ready: function () {
this.data = this.generateData();
},
generateData: function () {
var names = [], data = [];
for (var i = 0; i < this.count; i++) {
names.push(namegen.generateName(4, 8));
}
names.sort();
for (var i = 0; i < this.count; i++) {
data.push({
index: i,
sender: sender2[i],
textomsg: textomsg2[i],
datacriacao: datacriacao2[i],
senderfoto: senderfoto2[i]
});
}
return data;
},
tapAction: function (e) {
console.log('tap', e);
}
});
}
<%----%>
<template id="templateConversas" runat="server">
<div id="item" class="item {{ {selected: selected} | tokenList }}" ><%--onClick="conversa('{{name}}');"--%>
<div class="message" style="background-image: url({{senderfoto}});">
<span class="from"><br/>{{sender}}</span>
<span class="timestamp">{{datacriacao}}</span>
<div class="subject"><br/>{{textomsg}} </div><%--------Infinite List. {{index}}--%>
<%--<div class="body"><br/>Mensagem de teste...........</div>--%>
</div>
</div>
</template>
The problem is also reload the 'list-test'. if i call the js function after the list is loaded it doesn't apply the new data...
Your code isn't complete so it is hard to understand but I think that the problem is that you don't assign the result of the generateData() function to the template's model. Try following script for your component
Polymer('list-test', {
created: function () {
this.data = [];
},
refresh: function () {
this.data = this.generateData();
},
generateData: function () {
// your original code here
}
});
Now the list content should be updated with newly generated data when you call refresh() of the list-test element. To fill the list when element is created add
ready: function () {
this.refresh();
},