tl; dr : JavaScript로 MVC를 어떻게 구현하나요?JavaScript의 Model-View-Controller
JavaScript로 MVC를 구현하려고합니다. 나는 코드를 무수히하면서 봤지만 적절한 해결책을 찾지 못했다. (이 코드는 단지 "옳은 것"이라고 느끼지 않습니다.)
나는 지금 어떻게 할 것인가? 믿을 수 없을만큼 복잡하며 작동하기가 쉽지 않습니다 (그러나 이전에 가지고 있던 코드 더미보다 낫습니다). MVC의 목적에 어긋나는 추악한 해결 방법이 있습니다.
보라, 혼란, 당신이 정말로 용감 경우 :
// 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
};
}
하나가 청소기 방법으로 자바 스크립트에서 MVC를 구현 않는 방법
? 이 시스템을 개선하려면 어떻게해야합니까? 아니면 다른 패턴을 따라야할까요?
(4 년 후) AngularJS를 사용하십시오. –
MVC가 Javascript에서 작동하는 방식을 이해하려는 경우, 구현 방법을 묻는 것이 매우 합리적입니다. 너무 많은 개발자들은 실제로 작동하는 방식을 실제로 이해하지 못하고 프레임 워크를 사용합니다. – NobodyReally