Hello dear developers,
I have this code in builder pattern and I want to make a phone book ,
I want , when an user clicks on add button a contact would be added to DOM and push to records,
I need the name and number would be given from user and I wrote such a thing but I have probelm with
their scops and also adding to dom with this pattern
I wrote this phoneBook.addRecords(addContactName.value , addContactPhone.value);
but it has an error due to its scope,
I want those value to make an object with PhoneBookRecord(name, phone)
constructor and push them to records
array
also I want them to be happend after addContactButton
is clicked also after pushing them , I want them to be added in dom with builder
.
thank you all to help me in advanced.
function ElementBuilder(name) {
this.element = document.createElement(name);
this.text = function (text) {
this.element.textContent = text;
return this;
};
//others add here
this.setClass = function (className) {
this.element.className = className;
return this;
};
this.setType = function (type) {
this.element.type = type;
return this;
}
this.appendTo = function (container) {
container.append(this.element);
return this;
}
this.build = function () {
return this.element;
};
}
const builder = {
create: function (name) {
return new ElementBuilder(name);
},
};
function PhoneBookRecord(name, phone) {
this.name = name;
this.phone = phone;
}
function PhoneBook() {
this.records = [];
this.addRecords = function(name, number) {
let record = new PhoneBookRecord(name, number);
this.records.push(record);
}
//add search remove functions add here
}
function Render(container) {
this.container = container;
const phoneBook = new PhoneBook();
this.init = function () {
const h1 = builder
.create("h1")
.text("Phonebook App")
.setClass("title")
.appendTo(this.container);
//other elements add here
const search = builder
.create("input")
.setClass("search")
.setType("text")
.appendTo(this.container);
const addContactText = builder
.create("p")
.text("Add New Contact")
.setClass("addContactText")
.appendTo(this.container);
const addContactName = builder
.create("input")
.setClass("addContactName")
.setType("text")
.appendTo(this.container);
const addContactPhone = builder
.create("input")
.setClass("addContactPhone")
.setType("number")
.appendTo(this.container);
const addContactButton = builder
.create("button")
.setClass("addContactButton")
.text("Add")
.appendTo(this.container);
const hr = builder
.create("hr")
.appendTo(this.container);
phoneBook.addRecords(addContactName.value , addContactPhone.value);
console.log(phoneBook.records);
};
//other functions
document.onclick = function(e) {
if (e.target && e.target.classList.contains("addContactButton")){
phoneBook.addRecords(this.addContactName , this.addContactPhone);
}
}
}
const phoneBookContainer = document.getElementById("phone-book-container");
const app = new Render(phoneBookContainer);
app.init();