tl; dr: Come si implementa MVC in JavaScript in modo pulito?Model-View-Controller in JavaScript
Sto cercando di implementare MVC in JavaScript. Ho cercato su Google e riorganizzato con il mio codice innumerevoli volte ma non ho trovato una soluzione adeguata. (Il codice semplicemente non "sembra giusto".)
Ecco come me ne occuperò proprio adesso. È incredibilmente complicato ed è un problema lavorare con (ma ancora meglio della pila di codice che avevo prima). Ha brutte soluzioni alternative che sconfiggono lo scopo di MVC.
Ed ecco, il disordine, se siete veramente coraggiosi:
// 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
};
}
Come si fa a implementare MVC in JavaScript in un modo più pulito? Come posso migliorare questo sistema? O è questa la strada completamente sbagliata, dovrei seguire un altro schema?
(quattro anni più tardi) Utilizzare AngularJS. –
Se stavi solo cercando di capire come funziona MVC in Javascript, chiedere come implementarlo è perfettamente ragionevole. Troppi sviluppatori utilizzano ora i framework senza realmente capire come funzionano. – NobodyReally