Passing object variable to onchange event JS - javascript

I've been browsing around for an answer to this question for a little while now, but haven't found a solution. I need to pass an object to a function which is being fired "onChange" when a select option is chosen by a user. The current code is:
selecter.onchange = function(){
var runScript = $("#actionSel option:selected").attr('script');
console.log(runScript);
eval("("+runScript+")();");
}
The intention here is to store a function within the "script" attr of the options, which will then be run when that option is selected. However, for one of my functions I need to pass a variable from the parent scope on in order to interact with the server via websockets.
The function stored in the "Script" attribute is :
function(){ popConfirm("Restore User","Do you really want to restore the selected users? This will un-delete the selected deleted users.",function(r){ if(r)restoreUser(r,io); });
Essentially this verifies with the user that they want to do what they've selected, then passes the result to my restore user function. It also needs to pass the "io" object on. However, I'm getting an error which states that io is undefined.
Any ideas would be extremely helpful. Thanks!
As requested, here are some additional relative pieces of code showing where IO is introduced.
AdminIO = new io(servPath);
AdminIO.on('send_users',function(rows){
toggleLoad();
appendUsers(rows,AdminIO);
});
Within appendUsers there's another function which compiles the select list and its options, dropActions(), wherein the selector.onchange and other piece I posted before are introduced. The selector.onchange is part of the function that creates the dropdown list. The function(){ popConfirm() } is added as the function to run on selection of that item. The function to build the list is :
dropActions = function(bActions, lActions, options){
// bActions = {id: myID, text: "this is my action", elem: document.getElementById('getDiv'), action: function(){ /*mycode here */}}
// lActions = {text: "select me to run an action", action: function(){ /*mycode here */}}
bActions = bActions || null;
lActions = lActions || null;
options = options || {elem: document.body, id: null};
if(!bActions && !lActions){ console.error("No actions added or available."); return; }
var
selID = options.id,
starter = (selID) ? document.getElementById(selID) : options.elem,
optsBar = document.createElement("header"),
selecter = document.createElement("select");
starterSel = document.createElement("option");
optsBar.id = "actionSelH";
starterSel.innerText = "More Actions";
starterSel.setAttribute('script','javascript:void(0)');
selecter.id = "actionSel";
selecter.appendChild(starterSel);
for(var i= 0; bActions.length > i; i++){
var
buttonText = bActions[i].text,
buttonID = bActions[i].id || 'ACT'+i,
buttonAction = bActions[i].action,
button = document.createElement('div');
button.id = buttonID;
button.classList.add("actionButton");
button.innerText = buttonText;
button.onclick = buttonAction;
optsBar.appendChild(button);
}
for(var i= 0; lActions.length > i; i++){
var selText = lActions[i].text,
selScript = lActions[i].action,
option = document.createElement('option');
option.innerText = selText;
option.setAttribute('script',selScript);
selecter.appendChild(option);
}
selecter.onchange = function(){
var runScript = $("#actionSel option:selected").attr('script');
console.log(runScript);
eval("("+runScript+")();");
}
optsBar.appendChild(selecter);
$(optsBar).insertBefore('#user_list_table');
//$('#user_list_table').after(optsBar);
//$(starter).prepend(optsBar);
},
Hopefully more context helps!

Instead of using eval, you could use the function constructor and pass your parameters directly to that function:
var scriptFunction = new Function(r, io, runScript);
scriptFunction(r, io);
Of course, this code assume that r and io will always be the variable you are looking for. If this ain't the case, you'll have to write your own logic to take the variable from the parent scope and then pass them to the scriptFunction.
Update
If you are able ton change the provided script, you could also try to implicitly declare the variables r and io:
function(r, io){ popConfirm("Restore User","Do you really want to restore the selected users? This will un-delete the selected deleted users.",function(r, io){ if(r)restoreUser(r,io); });

Related

Plain OOP Javascript: Treating localStorage as an Array doesn't work?

I am trying to implement localStorage with my simple OOP todo list.
The fiddle is here: https://jsfiddle.net/b81t2789/
I thought I could just treat the local storage like an array and copy the logic I used with my actual array but that doesn't work.
Here, right after pushing the task into the array, I added a line that stores the task in the local storage and stringifies it:
// function that adds new task to the array
function pushArray(){
var newtask = new Task(toDo.value, "No note yet");
taskItems.push(newtask);
var storedTask = localStorage.setItem(newtask, JSON.stringify(newtask));
displayStorage(result2, storedTask);
displayArray(result, newtask.Name);
appendNote(result, newtask);
}
Then right below the function that displays the new array element I added one that retrieves the item from local storage, parses it, then creates a DOM element with the new task and appends it to another container.
//function that displays array elements
function displayArray(parent,obj){
var task = make("div","class","taskitem",obj);
parent.appendChild(task);
fadeIn(task);
}
//function that displays storage elements
function displayStorage(parent,obj){
var retrieveObject = localStorage.getItem(obj);
var parseTask = JSON.parse(retrieveObject);
var newDiv = make("div", "class", "newdiv", parseTask);
parent.appendChild(newDiv);
fadeIn(newDiv);
}
This doesn't work at all, not sure why, and then if I were to be able to get this to work how would I continue to go about storing and updating notes like I did in the array with local Storage? I thought this would be easy as I figured out how to make a todo with objects and arrays pretty quickly (when I thought it would be super difficult, but it's been a week now and I've made no progress!)
I guess these are the pitfalls of learning to code by yourself, any help would be much appreciated thank you!
Here is the full javascript code:
//getElementById shortcut
function grab(id) {
return document.getElementById(id);
}
// add eventlistener shortcut
var when = function() {
return function(obj, event, func) {
obj.addEventListener(event, func, false);
};
}();
//Custom function to create DOM elements and set their contents
function make(el,type,name,content){
var theElement = document.createElement(el);
theElement.setAttribute(type, name);
theElement.innerHTML = content;
return theElement;
}
//compute style shortcut
function setStyle(theElement){
return window.getComputedStyle(theElement);
}
//fade in shortcut.
function fadeIn(theElement){
var compute = setStyle(theElement).opacity;
theElement.style.opacity = 1;
}
/*****************************************************/
var toDo = grab("todo");
var result = grab("demo");
var demolist = grab("demolist");
var button = grab("btn");
// submit input on enter which fires function that pushes task into the array.
when(toDo, "keypress", function(event){
if (event.key == "Enter" || event.keyCode == 13) {
pushArray();
toDo.value = "";
}
});
// "SHOW ARRAY" FUNCTION to verify that the array is being updated (I like this better than using the console);
when(button, "click", function(event){
demolist.innerHTML = "";
for(i=0; i< taskItems.length; i++){
demolist.innerHTML += taskItems[i].Name + " " + taskItems[i].Note + "<br>";
}
});
function showNotes(theNote){
var defaultNote = "No note yet";
if(theNote){
}
}
var taskItems = [];
/*********************************************************/
//create Task object
function Task(name, note){
this.Name = name;
this.Note = note;
this.completed = false;
}
// function that adds new task to the array
function pushArray(){
var newtask = new Task(toDo.value, "No note yet");
taskItems.push(newtask);
displayArray(result, newtask.Name);
appendNote(result, newtask);
}
//function that displays array elements
function displayArray(parent,obj){
var task = make("div","class","taskitem",obj);
parent.appendChild(task);
fadeIn(task);
}
//function that displays notes
function appendNote(theElement,obj){
var newClassItem = make("input","class","tasknote");
theElement.appendChild(newClassItem);
when(newClassItem, "keypress", submitNote.bind(null, obj, newClassItem));
}
//function for submitting notes
function submitNote(task,noteInput){
if (event.key == "Enter" || event.keyCode == 13) {
task.Note = noteInput.value;
var newNote = make("div", "class", "hasNote", task.Note);
noteInput.parentNode.replaceChild(newNote, noteInput);
fadeIn(newNote);
when(newNote,"dblclick", function(){
newNote.parentNode.replaceChild(noteInput, newNote);
});
}
}
Being localStorage a key-value storage, depending on your needs, you are better off serializing (stringifying, whatever) the array and saving in a single index.
var tasks = [
'post the question on SO',
'describe it carefully',
'get a nice reply',
'implement the suggested solution'
];
If you really need to split it for performance reasons, you have to index them by a arbitrary index. If you have reordering it gets tricky and you can either reflush the whole set of tasks every time someone adds/edits/deletes/reorder the tasks (memory-efficient, but very CPU intensive) or save the indexes in a different key so you can reconstruct the order later, like:
var tasks = {
'task1': 'implement the suggested solution',
'task2': 'describe it carefully',
'task4': 'get a nice reply',
'task9': 'post the question on SO'
};
var tasksOrder = [9, 2, 4, 1];
The first idea is very simple to implement, but will give you problems with arbitrarily long lists, the second one is much more easy on the CPU but much harder to implement (and uses more memory). It depends on the specifics of your case.

Hold temporary data in JSON

I really need help with an aspect of my project. My ultimate goal is to capture the changes made by a user and once they select confirm, post it to SQL for updating. I will use AJAX and PHP for the latter part of the project but I thought JSON would be a great idea to hold all the changes made by a user (the first part).
I am new to JSON and I'm having trouble putting the results in one large object that will be transferred to the server when the user selects "OK". Can someone help me with the coding of this? Is JSON the best way to accomplish the goal (of storing temporary?
Heres what I have so far (just a snippet):
HTML
<div class="button" data-info='2' data-id='8-7' onclick=addDeskid(e)></div>
<div class="button" data-info='4' data-id='2-5' onclick=remDeskId()></div>
<div class="button" value="submit">submit</div>
JS
function addDeskId(e){
$adjustment;
userObject = $(this);
userObjectChange = 'CHANGE_SEAT_TO'; //This is what i will use with AJAX and PHP to determine the SQL statement
userObjectID = userObject.attr('data-info'); //This is the unique SQL ID for the object being modified
userObjectDeskID = userObject.attr('data-id'); //This is the attribute for the object being modified
userObjectSeatID = 9-4; //This is what the attribute is being modified to, for the question, ill make it a solid value
var addUserObject = new jsonAddTest(userObjectID, userObjectChange, userObjectDeskID, userObjectSeatID,);
//this is what the function is actually doing on the user side
//$dragObject.attr("data-id",newSeat); //change desk number for new user location
//$dragObject.attr("previousseat", "T");
//var extPass = e;
//moveOrSetupAccountLog(extPass);
}
function remDeskId(){
userObject = $dropObject.find('div.dragTest');
userObjectChange = 'REMOVESEAT'; //This is what i will use with AJAX and PHP to determine the SQL statement
userObjectID = userObject.attr('data-info'); //This is the unique SQL ID for the object being modified
userObjectDeskID = userObject.attr('data-id'); //This is the attribute for the object being modified
userObjectDeskIDVal = 0; //This is what the attribute is being modified to
var remUserObject = new jsonRemTest(userObjectID, userObjectChange, userObjectDeskID, userObjectDeskIDVal);
//this is what the function is actually doing on the user side
//userObject.attr({"data-id":""}); //remove desk number for new user location
//userObject.appendTo('#userPool');
}
//JSON functions test
function jsonRemTest(id, change, name, seat, value){
this.ID = id;
this.ChangeType = change;
this.Name = name;
this.Seat = seat;
this.setTo = value;
userMoves.push(jsonRemTest);
}
function jsonAddTest(id, change, name, desk, seat, previousseat, previousseatnewvalue){
this.ID = id;
this.ChangeType = change;
this.Name = name;
this.Seat = desk;
this.setTo = seat;
this.PreviousSeatValue = previousseat;
this.PreviousSeatNewValue = previousseatnewvalue;
userMoves.push(jsonAddTest);
}
console.log(JSON.stringify(userMoves));
I am getting the error: userMoves is undefined. I understand why this is happening but I don't know how to correct it.
TL;DR
Every time the user clicks on this button, it generates an array. I want to combine all the arrays into one object that contains all of them. When the user clicks on a submit button, the object is sent to the server using AJAX/PHP. Is this the best way to do this and if so, how do I combine the output of the JSON functions into one object in preparation for sending?
Thanks in advance
OK, Let's tackle this with some recommendations.
First off your onclick=addDeskid(e) is not properly cased to call your function and well, it is in the markup not the code, so let's address that.
I also changed your markup slightly to work with my event handlers better using a class for myAddButton and myRemButton, do what you will with that but I used it. I also added a button to get the results logged after all the events fired. This is the reason you get [] you have nothing in there when it gets logged. I did nothing with the submit, that is yours to handle (ajax call?)
<div class="button myAddButton" data-info='2' data-id='8-7'>add</div>
<div class="button myRemButton" data-info='4' data-id='2-5'>remove</div>
<div class="button mySubmitButton">submit</div>
<button id="ShowResults" type='button'>ShowResults</button>
Now the code - I re-engineered this to create a "class" for the object using makeClass. This is just one way but does allow for instance objects when needed and makes it easier to namespace some functions. I artificially put a private function in there just to demonstrate use as well as a public function. Note the the "this" inside that function is the instance object NOT a global object. (google makeClass with the attributed authors for more info)
I created a "class" with generic attributes. You COULD create different functions for "add" and "remove" instead of the SetChangeObject function - like one for each...I used a generic one so the "object" has the same signature.
Now the code: this is definitely a bit artificial in some places just to demonstrate use:
// makeClass - By Hubert Kauker (MIT Licensed)
// original by John Resig (MIT Licensed).
function makeClass() {
var isInternal;
return function (args) {
if (this instanceof arguments.callee) {
if (typeof this.init == "function") {
this.init.apply(this, isInternal ? args : arguments);
}
} else {
isInternal = true;
var instance = new arguments.callee(arguments);
isInternal = false;
return instance;
}
};
}
var SeatGroup = makeClass(); //create our class
//the method that gets called on creation instance object of class
SeatGroup.prototype.init = function (id, changeType, name, desk, seat, setToValue, previousseat, previousseatnewvalue) {
// a default value
var defaultSeat = "default";
var defaultName = "default";
this.ID = id;
this.ChangeType = changeType;
this.Name = name ? name : defaultName;
this.Desk = desk ? desk : "";
this.Seat = seat ? seat : privateFunction(defaultSeat);;
this.SetTo = setToValue ? setToValue : this.ID;
this.PreviousSeatValue = previousseat ? previousseat : "";
this.PreviousSeatNewValue = previousseatnewvalue ? previousseatnewvalue : "";
this.changeObject = {};
// public method
this.SetChangeObject = function () {
this.changeObject.ID = this.ID;
this.changeObject.ChangeType = this.ChangeType;
this.changeObject.Name = this.Name;
this.changeObject.Seat = this.Seat;
this.changeObject.Desk = this.Desk;
this.changeObject.SetTo = this.SetTo;
this.changeObject.PreviousSeatValue = this.PreviousSeatValue;
this.changeObject.PreviousSeatNewValue = this.PreviousSeatNewValue;
};
function privateFunction(name) {
return name + "Seat";
}
};
var userMoves = [];//global warning-global object!!
//event handlers
$('.myAddButton').on('click', addDeskId);
$('.myRemButton').on('click', remDeskId);
$('#ShowResults').on('click', function () {
console.log(JSON.stringify(userMoves));//log this after all are pushed
});
//function called with the "add" that can be customized
function addDeskId(e) {
var uo = $(this);//jQuery of the "myAddButton" element
var userObjectChange = 'CHANGE_SEAT_TO';
var userObjectID = uo.data('info');
var userObjectDeskID = uo.data('id');
var userObjectSeatID = '9-4';
// create a private instance of our class (calls init function)
var uChange = SeatGroup(userObjectID, userObjectChange, userObjectDeskID, userObjectSeatID);
uChange.SetChangeObject();//call public function
//log what we created
console.dir(uChange.changeObject);
//does not work, its private: console.log( uChange.privateFunction('hi'));
// push to our global
userMoves.push(uChange.changeObject);
}
// event function, customize as needed
function remDeskId() {
var userObject = $(this);
var userObjectChange = 'REMOVESEAT';
var userObjectID = userObject.data('info');//use jQuery data, easier/better
var userObjectDeskID = userObject.data('id');
var userObjectDeskIDVal = 0;
var remUserObject = SeatGroup(userObjectID, userObjectChange, userObjectDeskID);
remUserObject.PreviousSeatValue = "FreddySeat";//show how we set a properly of our object
remUserObject.SetChangeObject();//call public function
console.dir(remUserObject.changeObject);
userMoves.push(remUserObject.changeObject);
}
Play around with it here: http://jsfiddle.net/q43cp0vd/1/

Can we create a dialog box with a checkbox and a combobox using google closure

I am trying to create a dialog box with a checkbox, a user name and a combobox for roles which is enabled only when the checkbox is checked. I have the basic code running on a jsp page but how do i get it to work in a dialog box? All the components are rendered using google closure.
my js file
function combox ()
{
goog.events.listen((goog.dom.getElement('switch')), goog.events.EventType.CLICK,
function(e) {
var request = new goog.net.XhrIo();
var cb = new Array();
goog.events.listen(request, "complete", function(e){
var xhr = /** #type {goog.net.XhrIo} */ (e.target);
res = xhr.getResponseJson();
var mycount = count(res.myrole);
var content = new Array();
var userlist = new Array();
for(var k=0;k<mycount;k++)
{
content[k] = res.myrole[k].role;
}
var mycount1 = count(res.myusers);
for(var l=0;l<mycount;l++)
{
userlist[l] = res.myusers[l].user;
}
var child = new Array();
var container = goog.dom.getElement('c');
for(var m=0;m<userlist.length;m++)
{
child[m] = goog.dom.createDom('div',{'id':'user'+(m+1)},userlist[m]);
cb[m] = new goog.ui.ComboBox();
cb[m].setUseDropdownArrow(true);
for(var n=0;n<content.length;n++)
{
cb[m].addItem(new goog.ui.ComboBoxItem(content[n]));;
}
cb[m].render();
goog.dom.append(container, child[m]);
});
});
}
function count(obj) {
var count=0;
for(var user in obj) {
if (obj.hasOwnProperty(user)) {
++count;
}
}
return count;
}
I'm getting proper response from my servlet, but I want these components in a dialog box(i.e a checkbox,username and a combobox for each user retrieved from my servlet.)
You should look into using a goog.ui.Dialog - http://docs.closure-library.googlecode.com/git/class_goog_ui_Dialog.html
Here is a demo of how to use one : http://closure-library.googlecode.com/git/closure/goog/demos/dialog.html
After instantiating one, you would use the setContent method to place your form as the content html of the dialog.
You can also extend the goog.ui.editor.AbstractDialog class ( http://docs.closure-library.googlecode.com/git/class_goog_ui_editor_AbstractDialog.html ), which helps manage an internal reference to a goog.ui.Dialog rather than directly creating one and gives convenient hide and show methods.
__
As a sidenote, it's typically viewed as an anti-pattern in Javascript to use the "new Array()" syntax rather than var userList = []; for reasons specified here and elsewhere.

How to Associate an Object with a DOM Element

I have a master object in my JS setup, i.e.:
var myGarage = {
cars: [
{
make: "Ford",
model: "Escape",
color: "Green",
inuse: false
},
{
make: "Dodge",
model: "Viper"
color: "Red",
inuse: true
},
{
make: "Toyota",
model: "Camry"
color: "Blue",
inuse: false
}
]
}
Now I loop over my cars and put them in a table. In the table I also have a button that lets me toggle the car as "in use" and "not in use".
How can I associate the DOM Element of every row with its corresponding car, so that if I toggle the "inuse" flag, I can update the master object?
You can actually attach an object directly to a node:
var n = document.getElementById('green-ford-escape');
n.carObject = myGarage.cars[0];
n.onclick = function() {
doSomethingWith(this.carObject);
}
For the same of removing ambiguity, in some cases, it's more clear write the above event handler to refer to n instead of this:
n.onclick = function() {
doSomethingWith(n.carObject);
}
You can also refer directly to the object from the attached event:
var n = document.getElementById('green-ford-escape');
n.onclick = function() {
doSomethingWith(myGarage.cars[0]);
}
In the latter case, myGarage does not have to be global. You can do this and expect it to work correctly:
(function(){
var myGarage = { /* ... etc ... */ };
var n = document.getElementById('green-ford-escape');
n.onclick = function() {
doSomethingWith(myGarage.cars[0]);
}
})();
The node's event function will "hold onto" the local variable correctly, effectively creating a private variable.
You can test this in your Chrome/FF/IE console:
var o = {a: 1};
var n = document.createElement('div');
n.innerHTML = "click me";
n.data = o;
n.onclick = function() { n.data.a++; console.log(n.data, o); }
document.body.appendChild(n);
You should see the console log two identical objects with each click, each with incrementing a values.
Beware that setting n.data to a primitive will not create a reference. It'll copy the value.
I'd suggest considering addEventListener, and a constructor that conforms your objects to the eventListener interface.
That way you can have a nice association between your object, your element, and its handlers.
To do this, make a constructor that's specific to your data.
function Car(props) {
this.make = props.make;
this.model = props.model;
// and so on...
this.element = document.createElement("div"); // or whatever
document.body.appendChild(this.element); // or whatever
this.element.addEventListener("click", this, false);
}
Then implement the interface:
Car.prototype.handleEvent = function(e) {
switch (e.type) {
case "click": this.click(e);
// add other event types if needed
}
}
Then implement your .click() handler on the prototype.
Car.prototype.click = function(e) {
// do something with this.element...
this.element.style.color = "#F00";
// ...and the other properties
this.inuse = !this.inuse
}
So then you can just loop over the Array, and make a new Car object for each item, and it'll create the new element and add the listener(s).
myGarage.cars.forEach(function(obj) {
new Car(obj)
})
You can use HTML5 data-* attribute to find out which row it is. You must be doing something like this
var table = $('<table>'); // Let's create a new table even if we have an empty table in our DOM. Simple reason: we will achieve single DOM operation (Faster)
for (var i=0; i<myGarbage.cars.length; i++) {
// Create a new row and append to table
var tr = $('<tr>').appendTo(table);
var carObject = myGarbage.cars[i];
// Traverse the JSON object for each car
for (var key in carObject) {
// Create other cells. I am doing the last one
var td = $('<td>').appendTo(tr);
var button = $('<button>').attr('data-carId', i).addClass('toggle-inuse').appendTo(td);
}
}
// If en ampty table awaits me in DOM
$('#tableId').html(table.html());
Now we will add event listener on button :-
$('.toggle-inuse').click(function() {
var i = $(this).data('carId');
myGarbage.cars[i].inuse = !myGarbage.cars[i].inuse; //Wow done
}
Try this out !!
You'll want some sort of ID or distinct row in your information, else you'll have to rely on the array index to do this. Either way you'll want to store the data using data attributes.
So when you loop through:
for (var i = 0, l = array.length; i < l; i++) {
var div = '<tr data-car="' + JSON.stringify(array[i]) + '" data-index="' + i + '"><td></td></tr>'
}
And on your click event:
$('button').click(function() {
var carIndex = $(this).closest('tr').attr('data-index');
var carData = $(this).closest('tr').attr('data-car');
if (carData) carData = JSON.parse(carData);
myGarage.cars[carIndex].inUse = true;
})
If you bind the data to the DOM, you may not even need to update the actual JS data. Could go over each row in the table and re-create the data-object you created the table from.

JavaScript closures and variable scope

I am having trouble with JS closures:
// arg: an array of strings. each string is a mentioned user.
// fills in the list of mentioned users. Click on a mentioned user's name causes the page to load that user's info.
function fillInMentioned(mentions) {
var mentionList = document.getElementById("mention-list");
mentionList.innerHTML = "";
for (var i = 0; i < mentions.length; i++) {
var newAnchor = document.createElement("a");
// cause the page to load info for this screen name
newAnchor.onclick = function () { loadUsernameInfo(mentions[i]) };
// give this anchor the necessary content
newAnchor.innerHTML = mentions[i];
var newListItem = document.createElement("li");
newListItem.appendChild(newAnchor);
mentionList.appendChild(newListItem);
}
document.getElementById("mentions").setAttribute("class", ""); // unhide. hacky hack hack.
}
Unfortunately, clicking on one of these anchor tags results in a call like this:
loadUserNameInfo(undefined);
Why is this? My goal is an anchor like this:
<a onclick="loadUserNameInfo(someguy)">someguy</a>
How can I produce this?
Update This works:
newAnchor.onclick = function () { loadUsernameInfo(this.innerHTML) };
newAnchor.innerHTML = mentions[i];
The "i" reference inside the closure for the onclick handlers is trapping a live reference to "i". It gets updated for every loop, which affects all the closures created so far as well. When your while loop ends, "i" is just past the end of the mentions array, so mentions[i] == undefined for all of them.
Do this:
newAnchor.onclick = (function(idx) {
return function () { loadUsernameInfo(mentions[idx]) };
})(i);
to force the "i" to lock into a value idx inside the closure.
Your iterator i is stored as a reference, not as a value and so, as it is changed outside the closure, all the references to it are changing.
try this
function fillInMentioned(mentions) {
var mentionList = document.getElementById("mention-list");
mentionList.innerHTML = "";
for (var i = 0; i < mentions.length; i++) {
var newAnchor = document.createElement("a");
// Set the index as a property of the object
newAnchor.idx = i;
newAnchor.onclick = function () {
// Now use the property of the current object
loadUsernameInfo(mentions[this.idx])
};
// give this anchor the necessary content
newAnchor.innerHTML = mentions[i];
var newListItem = document.createElement("li");
newListItem.appendChild(newAnchor);
mentionList.appendChild(newListItem);
}
document.getElementById("mentions").setAttribute("class", "");
}

Categories