tl; dr: Jak jeden wdrożyć MVC w JavaScript w czysty sposób?Model-widok kontroler w JavaScript
Próbuję zaimplementować MVC w JavaScript. Przeszukałem go i zreorganizowałem z moim kodem niezliczoną ilość razy, ale nie znalazłem odpowiedniego rozwiązania. (Kod po prostu nie "czuje się dobrze").
Oto, jak to teraz robię. Jest to niewiarygodnie skomplikowane i sprawia ból (ale wciąż lepszy od stosu kodu, który miałem wcześniej). Ma brzydkie obejścia tego rodzaju, które pokonują cel MVC.
A oto bałagan, jeśli jesteś naprawdę odważny:
// 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
};
}
jaki sposób można wdrożyć MVC w JavaScript w czystszym sposób? Jak mogę ulepszyć ten system? Czy jest to całkowicie niewłaściwa droga, czy powinienem zastosować inny wzór?
(cztery lata później) Użyj AngularJS. –
Jeśli próbujesz zrozumieć, jak działa MVC w JavaScript, to pytanie, jak go wdrożyć, jest całkowicie uzasadnione. Zbyt wielu programistów używa teraz frameworków bez zrozumienia, jak działają. – NobodyReally