In ES5 I create a Model-View-Controller structure by using IIFEs and reveal module pattern.
var model = function () { ... }()
var view = function () { ... }()
var controller = function (model, view) {
view.functionname(var one);
......
}(model, view)
The new block scope {} in ES6 can replace IIFEs, but how we call the functions/methods of the model/view from the controller ?
To combine multiple javascripts in ES5 and avoid naming collision I use an expression:
;( code ...)
How can be this done in ES6 ?
答案 0 :(得分:1)
Maybe something like this?
class View {
exampleMethod() {
console.log("view's example method called")
}
}
class Model {
exampleMethod() {
console.log("model's example method called")
}
}
class Controller {
constructor(view,model) {
this.view = view
this.model = model
console.log("Test")
}
exampleMethod() {
this.view.exampleMethod()
this.model.exampleMethod()
}
}
const myView = new View()
const myModel = new Model()
const myController = new Controller(myView,myModel)
myController.exampleMethod()
To avoid name collision in ES6 you could wrap everything into
(()=>{
// Code...
})()
答案 1 :(得分:1)
ES6中的新块范围可以取代IIFE
不是真的。它可以取代仅仅引入范围的IIFE,但它不能取代模块模式 - 块没有返回值。它也没有任何论据。你可以只使用全局变量:
var model, view, controller;
{
model = {…};
}
{
view = {…};
}
{
let one = …;
view.functionname(one);
controller = {…};
}
但说实话,这很奇怪 1 。我们没有理由不使用自ES3以来我们所知道的完全相同的揭示模块模式。
1:一个可行的替代方案是ES6模块,它允许循环依赖,并为所有这些提供更好的语法