How do I refactor this to use OOP , with MVC pattern:
function () {
var dataToImage = { 'a': 'a.gif', 'b': 'something.gif' };
var currentimage = dataToImage['a'];
function setCurrentImage(e){ currentImage = e.src; }
function getMousePosition(){ }
function drawToolbar {
for(i in dataToImage){
document.write('<img src="'+dataToImage[i]+'" onclick="setCurrentImage(this);">');
}
document.write('<div onclick="drawImage(this,getMousePosition())"></div>');
return;
}
function drawImage(div,xy) {
var img = document.createElement('div');
div.style["left"] = xy[0];
div.style["top"] = xy[1];
img.innerHTML='<img src="'+currentImage+'">');
div.appendChild(img);
return;
}
drawToolbar();
}());
There's a really good article on this here. I won't repeat what it says here. But to get you started you might extract a Model like this:
And your controllers might be something like:
Your views would be pretty much as your drawImage and drawToolbar functions are now, except the data they render would be passed as parameters. For example:
Then you can wire things up with events as appropriate. (Use addEvent and don't set events with onclick attributes on html elements.)