Tuesday, May 29, 2018

Model-View-Controller in JavaScript

tl;dr: How does one implement MVC in JavaScript in a clean way?



I'm trying to implement MVC in JavaScript. I have googled and reorganized with my code countless times but have not found a suitable solution. (The code just doesn't "feel right".)



Here's how I'm going about it right now. It's incredibly complicated and is a pain to work with (but still better than the pile of code I had before). It has ugly workarounds that sort of defeat the purpose of MVC.



And behold, the mess, if you're really brave:



// Create a "main model"
var main = Model0();

function Model0() {
// Create an associated view and store its methods in "view"
var view = View0();

// Create a submodel and pass it a function
// that will "subviewify" the submodel's view
var model1 = Model1(function (subview) {
view.subviewify(subview);
});

// Return model methods that can be used by
// the controller (the onchange handlers)
return {
'updateModel1': function (newValue) {
model1.update(newValue);
}
};
}

function Model1(makeSubView) {
var info = '';

// Make an associated view and attach the view
// to the parent view using the passed function
var view = View1();
makeSubView(view.__view); // Dirty dirty

// Return model methods that can be used by
// the parent model (and so the controller)
return {
'update': function (newValue) {
info = newValue;

// Notify the view of the new information
view.events.value(info);
}
};
}

function View0() {
var thing = document.getElementById('theDiv');
var input = document.getElementById('theInput');

// This is the "controller", bear with me
input.onchange = function () {
// Ugly, uses a global to contact the model
main.updateModel1(this.value);
};

return {
'events': {},

// Adds a subview to this view.
'subviewify': function (subview) {
thing.appendChild(subview);
}
};
}

// This is a subview.
function View1() {

var element = document.createElement('div');
return {
'events': {
// When the value changes this is
// called so the view can be updated
'value': function (newValue) {
element.innerHTML = newValue;
}
},

// ..Expose the DOM representation of the subview
// so it can be attached to a parent view
'__view': element
};
}


How does one implement MVC in JavaScript in a cleaner way? How can I improve this system? Or is this the completely wrong way to go, should I follow another pattern?

No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...