Refactor to use OOP MVC

2019-04-16 17:33发布

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();
}());

1条回答
ら.Afraid
2楼-- · 2019-04-16 17:58

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:

var Images {
    get: function(id) {
        return this.data[id];
    },
    del: function(id) {
        delete this.data[id];
        // might make an ajax call here to update the data serverside...
    },
    'data': {
        'a': 'a.gif', 
        'b': 'something.gif'
    }
};

And your controllers might be something like:

Controllers.DrawToolbar = function () {
    // get the data for the images and pass it to the toolbar view
};

Controllers.DrawImage = function() {
    // get the data for the image and pass it to the image view
};

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:

Views.Image = function (target, data, x, y) {
    var imgContainer = document.createElement('div'),
        img = document.createElement('img');
    imgContainer.appendChild(img);
    target.style["left"] = x;
    target.style["top"] = y;
    img.src = data;
    target.appendChild(imgContainer);
};

Then you can wire things up with events as appropriate. (Use addEvent and don't set events with onclick attributes on html elements.)

查看更多
登录 后发表回答