I want to implement MVC of a button. I have created a button using
var btn = {btnElem : document.createElement('button')} ;
now i want to inherit this button into different types of buttons like arthimetic or logical button. so I used this btn object to get the arthimetic button var parent = Object.create(btn);
var arthButn = {btnElem : parent.btnElem};
. Now I want to display arthButn s looping from 0-9 numbers.
But it only shows one button.
buttonContainer = document.createElement('div');
for(var i=0;i<10;i++){
arthButn.btnElem.innerHTML = i;
buttonContainer.appendChild(arthButn.btnElem);
}
If i use document.createElement('button') in place of arthButn.btnElem it works fine. But in this approach, the multiple elements are not appended to the buttonContainer div. Buttons are replacing one on the other and only one button is shown.
Other issue is that I want to append event handler to the arthbtn on its controller file. So how to resolve this issue.
The problem is that you are not creating 10 button elements as you expect, you are creating only one.
When you create the base prototype object
var btn = { btnElem: document.createElement('button') }
var parent = Object.create(btn);
you create a single DOM element. Then you create an object which uses the btn
object as a prototype
var arthBtn = { btnElem: parent.btnElem }
Note that arthBtn.btnElem
is equal to parent.btnElem
which is equal to btn.btnElem
by reference. So, in your loop, you are modifying the innerHTML
of the same DOM button element, and then appending that same element to the container.
Here is a possible solution: https://jsfiddle.net/oz0ppkm5/. Instead of having a prototype property, use a prototype method which returns a new DOM element every time it's called.
EDIT: This fiddle better illustrates how you could achieve inheritance: https://jsfiddle.net/o52mn65q/.