tl;dr:如何以干净的方式在 JavaScript 中实现 MVC?
我正在尝试在 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
};
}
如何以更简洁的方式在 JavaScript 中实现 MVC?我怎样才能改进这个系统?或者这是完全错误的方法,我应该遵循另一种模式吗?
最佳答案
至少有几个已建立且可用的 JavaScript MVC 框架 JavaScriptMVC和 pureMVC .可能还有更多。我已经将 JavaScriptMVC 用于基于浏览器的应用程序和 Air 应用程序,并不断回来使用它——它有它的问题,但我发现它非常有用。
还有其他解决方案,看看Sammy ,我听说过的一件好事。我还没有用过自己,但打算尽快尝试。我对它的了解还不够,无法正确描述它,但对我来说,它看起来像是一个在路由、模板系统和 ReSTful 数据存储上工作的前端 Controller 。我不确定它是否是 MVC,但具有相似的成分。
我不同意mway's answer . MVC 在 JavaScript 中的实现可能有点不同,但它的好处对 organising this mess 非常重要。 .通常与 OO 语言相关的设计模式不会仅仅因为 js 不是基于类的就消失了。
我会说 MVC 比基于请求的(服务器端)应用程序更适合 JavaScript 应用程序。这些对象可能会在单页 JavaScript 应用程序中停留一段时间——如果不是几小时,也可能是几分钟——并且采用一种组织良好的方式来组织它们的交互将使您的代码更加健壮且易于处理。 There are books on the subject.
关于您发布的代码的其他几点。
- View 对象负责将事件监听器应用于 DOM 元素。这是 Controller 的工作。 View 仅呈现 HTML - Controller 监听事件并采取相应行动。
- 您的模型似乎了解您的观点。模型层应该对 View 层有最少的了解(可能被注册为 observers )。保持你的模型简洁明了,我的意思是业务点 - 业务逻辑。在 js 应用程序中,您可能只是代理服务器端模型层,但保持模型符合业务逻辑而不是其他任何东西对您的理智很重要。应用程序逻辑是 Controller 的工作
关于javascript - JavaScript 中的模型- View - Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3035506/