1

I've tried to look for a similar question and either can't phrase it properly or I'm being rather silly. I'm relatively new to JavaScript, and have a question about creating multiple object instances:

Here it is:

Say you're trying to build a 'list builder' dynamically with javascript. You create multiple lists and add items to them. So you build a class like so (note, the code is mostly illustrative to try and clarify the question):

var dynamicList = function(listName){
    this.listTitle = listName;
}

dynamicList.prototype = {

    buildList : function(){
        var template = $('<ul id="'+ this.listTitle +'"></ul>').append('<h2>' + this.listTitle + '</h2>';
        $(body).append(template);
    }

}

now here comes the question:

Say I use an input form to create the list wrapper, and each time they submit the form, a new list is born. How is this managed? What I would presume would need to happen would be creating a new object each time:

var list1 = new dynamicList("[user input title from form]"); //first list
list1.buildList();

var list2 = new dynamicList("[user input title from form]"); //second list
list2.buildList();

var list3 = new dynamicList("[user input title from form]"); //third list
list3.buildList();    

var list[n] ... // and so on
list[n].buildList();

But I can't figure out how to do this. Can I dynamically create variable names, or how would one approach this problem? Would you wrap it in a higher level object and create an increment system for each list created? Is this even a problem, or could you just recursively use var list = new dynamicList for each form?

I hope I have framed my issue in a way that everyone can understand, thanks for taking the time to read through it. I'd also appreciate any suggestions as to how to structure the code to ensure utmost scalability.

Thanks!

1 Answer 1

2

If you want to have n of something and be able to reference them - put them into an array.

var myLists = []; //Shorthand for new Array()

var list = new DynamicList("[user input title from form]"); //first list
list.buildList()
myLists.push(list);

list = new DynamicList("[user input title from form]"); //second list
list.buildList()
myLists.push(list);

You could also get rid of the buildList() call by creating a constructor.

Sign up to request clarification or add additional context in comments.

1 Comment

Ah! I see. And I could just push the list items and their attributes as JSON. Thanks! I have a better grasp as to how to structure it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.