tl; dr: Làm cách nào để triển khai MVC trong JavaScript một cách rõ ràng?Model-View-Controller trong JavaScript
Tôi đang cố triển khai MVC bằng JavaScript. Tôi đã googled và tổ chức lại với mã của tôi vô số lần nhưng đã không tìm thấy một giải pháp phù hợp. (Mã chỉ không "cảm thấy đúng".)
Đây là cách tôi đang thực hiện nó ngay bây giờ. Nó cực kỳ phức tạp và là một nỗi đau để làm việc với (nhưng vẫn tốt hơn so với đống mã tôi đã có trước đây). Nó có cách giải quyết xấu xí để đánh bại mục đích của MVC.
Và kìa, sự lộn xộn, nếu bạn thực sự dũng cảm:
// 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
};
}
Làm sao người ta thực hiện MVC trong JavaScript trong một cách sạch hơn? Làm thế nào tôi có thể cải thiện hệ thống này? Hay đây là con đường hoàn toàn sai lầm, tôi có nên theo một mô hình khác không?
(bốn năm sau) Sử dụng AngularJS. –
Nếu bạn chỉ cố gắng hiểu MVC hoạt động như thế nào trong Javascript, thì hãy hỏi cách triển khai nó là hoàn toàn hợp lý. Quá nhiều nhà phát triển sử dụng các khung công tác ngay bây giờ mà không thực sự hiểu cách chúng hoạt động. – NobodyReally