Javascript &引用;“你好,世界”;在MVC模式中

Javascript &引用;“你好,世界”;在MVC模式中,javascript,model-view-controller,design-patterns,object-oriented-analysis,Javascript,Model View Controller,Design Patterns,Object Oriented Analysis,在某公司的面试中,我被问到这个问题 你们知道什么样的设计模式……然后我被告知要基于MVC设计模式编写最简单的“hello world”应用程序 我想出了一个JavaScript程序 var arr = ["a","b","c","d"]; // this is an array, same as store or model alert(arr[0]); // this is controller //and browser alert is a view.

在某公司的面试中,我被问到这个问题

你们知道什么样的设计模式……然后我被告知要基于MVC设计模式编写最简单的“hello world”应用程序

我想出了一个JavaScript程序

var arr = ["a","b","c","d"];   // this is an array, same as store or model
alert(arr[0]);                // this is controller
//and browser alert is a view.
后来我被告知警报是一种视图。我所知道的MVC的基本概念是,模型中的任何更改都要报告给视图。中间有一个控制器来调用这些方法

您能否纠正我的方法,或者为hello world MVC应用程序提供一个替代解决方案。还要解释MVC的微妙方面

谢谢

var M = {}, V = {}, C = {};

M.data = "hello world";

V.render = function (M) { alert(M.data); }

C.handleOnload = function () { V.render(M); }

window.onload = C.handleOnLoad;
控制器(
C
)监听某种交互/事件流。在本例中,这是页面的加载事件

模型(
M
)是数据源的抽象

视图(
V
)知道如何渲染模型中的数据

控制器告诉视图对模型中的内容执行某些操作

在这个例子中

  • 视图除了实现一些接口之外,对模型一无所知
  • 模型对视图和控制器一无所知
  • 控制器了解模型和视图,并告诉视图对模型中的数据进行处理

注:上述示例是为了演示目的而进行的严格简化。对于JS MVC世界中真实的“hello world”示例,请看一下

,我认为您有点忽略了这里的要点

MVC是一种用于设计应用程序的模式。我认为,至少您希望能够更改模型,并看到视图中反映的更改

您通常会有一个对象来表示模型,一个不同的对象来表示“视图”(它可能会在模型和用作视图的HTML对象之间进行调解),还有一个控制器,它会从HTML对象获取输入并更新模型

因此,更改编辑字段时,编辑字段会通知控制器,控制器会更新模型,模型会触发控制器用于更新依赖于此数据的任何其他视图组件的事件


要实现“hello world”版本还需要几行代码,但我想这正是我从这样一个面试问题中寻找的。MVC是一种设计模式,应该用于构建应用程序。MVC代表模型、视图、控制。它基本上是说,您应该将业务逻辑(模型)与用户界面(视图)和控制逻辑分开

例如:

您有一个用户类,从数据库加载用户,可以保存em。这是您的模型

您有一个使用User类登录用户的控制器

控制器完成后,将显示一个包含文本“Welcome$username”的模板

此外,模型不应该知道视图和控制器,视图不应该知道控制器,而控制器知道模型和视图

MVC上的维基百科:

更好的例子

var M = {}, V = {}, C = {};

/* Model View Controller Pattern with Form Example */


/* Controller Handles the Events */

M = {
    data: {
        userName : "Dummy Guy",
        userNumber : "000000000"
    }, 
    setData : function(d){
        this.data.userName = d.userName;
        this.data.userNumber = d.userNumber;
    },
    getData : function(){
        return data;
    }
}

V = {
    userName : document.querySelector("#inputUserName"),
    userNumber : document.querySelector("#inputUserNumber"),
    update: function(M){
        this.userName.value = M.data.userName;
        this.userNumber.value = M.data.userNumber;
    }
}

C = {
    model: M,
    view: V,
    handler: function(){
        this.view.update(this.model);
    }
}

document.querySelector(".submitBtn").addEventListener("click", function(){
    C.handler.call(C);
}); 

/* Model Handles the Data */

/* View Handles the Display */
MVC架构 我写了一篇关于MVC架构的文章。这里只提供了一些代码,希望对大家有所帮助



从上面的例子中,我们可以理解,在这个设计中有三个不同的单元,每个单元都有一个特定的任务要执行。让我们从上面的基础结构构建MVC设计。可以有多个视图和观察者,这里只会首先创建另一个视图



这里要理解的是,模式不能依赖于视图或查看器,也不能依赖于对数据执行的操作。数据模式可以独立,但视图和控制器是必需的,因为一个需要显示数据,另一个需要操作数据。因此,视图和控制器的创建是因为模态,而不是相反



从上面可以看出,视图和控制器之间已经建立了链接。这也是MVC模式的要求之一。为了演示模态的变化,让我们改变程序,观察模态状态的变化是独立完成的,并反映在视图中

//Modal
function Modal(){
this.state = 0;
this.data = ["JS is object based language","JS implements prototypal inheritance"];
//
this.getState = function (){
    return this.state;
};
this.changeState = function (value) {
    this.state = value;
};
}

// View is created with modal
function View(m) {
    this.modal = m;
    this.display = function () {
        console.log("***********************************");
        console.log(this.modal.data[modal.getState()]);
        console.log("***********************************");
    };
}
//controller is created with the view
function Controller(v){
    this.view = v;
    this.updateView = function(){
        // update the view
        this.view.display();
    };
}
// Test
var modal = new Modal();
var consoleView = new View(modal);
var controller = new Controller(consoleView);
controller.updateView();
// change the state of the modal
modal.changeState(1);
controller.updateView();

当模式的状态更改时,控制器已向视图发送消息以更新自身。这很好,但还有一个主要概念有待实现,即需要通过模态识别观测器或控制器。为了看到这种情况发生,模态和控制器之间必须有一个链接,以便任何数量的控制器都能显示出对模态的兴趣,这被认为是将观察者注册到模态。这种关系是利用空中不存在观察者的概念来实现的。它的存在是因为对模态感兴趣,因此当它被创建时,它必须使用模态来创建,它需要显示兴趣,或者换句话说,它可以访问模态。让我们看看下面的示例,看看如何使用JavaScript简单而优雅地实现这个MVC设计模式

function Modal(){
    var stateChanged =  false;
    var state = 0;
    var listeners = [];
    var data = ["JS is object based language","JS implements prototypal inheritance"];
    // To access the data
    this.getData = function(){
        return data;
    };
    // To get the current state
    this.getState = function (){
        return state;
    };
    // For simplicity sake we have added this helper function here to show 
    // what happens when the state of the data is changed
    this.changeState = function (value) {
            state = value;
        stateChanged = true;
        notifyAllObservers();
    };
    // All interested parties get notified of change
    function notifyAllObservers (){
    var i;
        for(i = 0; i < listeners.length; i++){
            listeners[i].notify();
        }
    };
    // All interested parties are stored in an array of list
    this.addObserver = function (listener){
        listeners.push(listener);
    };
}

// View class, View is created with modal

function View(m) {
    this.modal = m;
    this.display = function () {
        console.log("***********************************");
        var data = this.modal.getData();
        console.log(data[modal.getState()]);
        console.log("***********************************");
    };
}


// Controller or Observer class has access to both modal and a view
function Controller(m,v){
    this.view = v;
    this.modal = m;
    this.modal.addObserver(this);

    // update view
    this.updateView = function(){
        this.view.display();
    };
    // Receives notification from the modal
    this.notify = function(){
        // state has changed
        this.updateView();
    };
}

// Test
var modal = new Modal();
var consoleView = new View(modal);
var controller = new Controller(modal,consoleView);
// change the state of the modal
modal.changeState(1);
modal.changeState(0);
modal.changeState(1);
modal.changeState(0);
函数模态(){
var stateChanged=false;
var状态=0;
var侦听器=[];
var data=[“JS是基于对象的语言”,“JS实现原型继承”];
//访问数据
this.getData=函数(){
返回数据;
};
//获取当前状态
this.getState=函数(){
返回状态;
};
//为了简单起见,我们在这里添加了这个helper函数来显示
//当数据的状态改变时会发生什么
this.changeState=函数(值){
状态=值;
stateChanged=true;
notifyAllobserver();
};
//所有相关方都会收到变更通知
函数notifyAllobserver(){
var i;
对于(i=0;i//Modal
var modal = { 
data : ["JS in object based language"," JS implements prototypal   inheritance"]
};

// View is created with modal
function View(m) {
    this.modal = m;
    this.display = function () {
        console.log("***********************************");
        console.log(this.modal.data[0]);
        console.log("***********************************");
    };
}

function Controller(v){
    this.view = v;
    this.informView = function(){
        // update the modal
        this.view.display();
    };
}
// Test
var consoleView = new View(modal);
var controller = new Controller(consoleView);
controller.informView();
//Modal
function Modal(){
this.state = 0;
this.data = ["JS is object based language","JS implements prototypal inheritance"];
//
this.getState = function (){
    return this.state;
};
this.changeState = function (value) {
    this.state = value;
};
}

// View is created with modal
function View(m) {
    this.modal = m;
    this.display = function () {
        console.log("***********************************");
        console.log(this.modal.data[modal.getState()]);
        console.log("***********************************");
    };
}
//controller is created with the view
function Controller(v){
    this.view = v;
    this.updateView = function(){
        // update the view
        this.view.display();
    };
}
// Test
var modal = new Modal();
var consoleView = new View(modal);
var controller = new Controller(consoleView);
controller.updateView();
// change the state of the modal
modal.changeState(1);
controller.updateView();
function Modal(){
    var stateChanged =  false;
    var state = 0;
    var listeners = [];
    var data = ["JS is object based language","JS implements prototypal inheritance"];
    // To access the data
    this.getData = function(){
        return data;
    };
    // To get the current state
    this.getState = function (){
        return state;
    };
    // For simplicity sake we have added this helper function here to show 
    // what happens when the state of the data is changed
    this.changeState = function (value) {
            state = value;
        stateChanged = true;
        notifyAllObservers();
    };
    // All interested parties get notified of change
    function notifyAllObservers (){
    var i;
        for(i = 0; i < listeners.length; i++){
            listeners[i].notify();
        }
    };
    // All interested parties are stored in an array of list
    this.addObserver = function (listener){
        listeners.push(listener);
    };
}

// View class, View is created with modal

function View(m) {
    this.modal = m;
    this.display = function () {
        console.log("***********************************");
        var data = this.modal.getData();
        console.log(data[modal.getState()]);
        console.log("***********************************");
    };
}


// Controller or Observer class has access to both modal and a view
function Controller(m,v){
    this.view = v;
    this.modal = m;
    this.modal.addObserver(this);

    // update view
    this.updateView = function(){
        this.view.display();
    };
    // Receives notification from the modal
    this.notify = function(){
        // state has changed
        this.updateView();
    };
}

// Test
var modal = new Modal();
var consoleView = new View(modal);
var controller = new Controller(modal,consoleView);
// change the state of the modal
modal.changeState(1);
modal.changeState(0);
modal.changeState(1);
modal.changeState(0);
function Modal(){
var stateChanged =  false;
var state = 0;
var listeners = [];
var data = [
"JS is object based language","JS implements prototypal inheritance",
"JS  has many functional language features", "JS is loosely typed language",
"JS still dominates the Web", "JS is getting matured ","JS shares code               
through prototypal inheritance","JS has many useful libraries like JQuery",
"JS is now known as ECMAScript","JS is said to rule the future of Web for      
many years"];

//
this.getData = function(){
    return data;
};
//
this.getState = function (){
    return state;
};

this.changeState = function (value) {
    state = value;
    stateChanged = true;
    notifyAllObservers();
};

function notifyAllObservers (){
var i;
    for(i = 0; i < listeners.length; i++){
        listeners[i].notify();
    }
}
this.addObserver = function (listner){
    listeners.push(listner);
};
}

// View is created with modal

function View(m) {
    this.modal = m;
    this.display = function () {
    console.log("****************************************************");
        var data = this.modal.getData();
        console.log(data[modal.getState()]);
    };
    //Adding external simulation of user sending input 

    this.pressButton = function(){
        var seed = 10;
        var number = Math.round(Math.random() * seed) ;
        // change the state of modal
        this.modal.changeState(number);
    };
}
// Controller class needs modal and view to communicate

function Controller(m,v){
    this.view = v;
    //console.log(this.view.display);
    this.modal = m;
    this.modal.addObserver(this);

    this.updateView = function(){
        // update the view
        //console.log(this.view);
        this.view.display();
    };
    this.notify = function(){
        // state has changed
        this.updateView();
    };
}

// Test
var modal = new Modal();
var consoleView = new View(modal);
var controller = new Controller(modal,consoleView);
// change the state of the modal
for ( var i = 0 ; i < 10; i++){
    consoleView.pressButton();
}
    function Modal(){
var stateChanged =  false;
var listeners = [];
var data = ["JS is object based language"];
// To retrieve the data
this.getData = function(){
    return data;
};
// To change the data by any action
this.modifyData = function (string) {
    ( data.length === 1 )? data.push(string): data.unshift(string);
    stateChanged = true;
    notifyAllObservers();
};

// Notifies all observers
function notifyAllObservers (){
var i;
    for(i = 0; i < listeners.length; i++){
        listeners[i].notify();
    }
}
// Requires to register all observers
this.addObserver = function (listener){
    listeners.push(listener);
};
}
// View is created with modal
function View(m) {
    this.modal = m;
    this.display = function () {
    console.log("****************************************************");
        var data = this.modal.getData();
        console.log(data[0]);
    console.log("****************************************************");
    };
    //Adding external simulation of user sending input 
    this.pressButton = function(string){
        // change the state of modal
        this.modal.modifyData(string);
    };
}

// View class

function Controller(m,v){
    this.view = v;
    this.modal = m;
    this.modal.addObserver(this);

    // Updates the view
    this.updateView = function(){
        this.view.display();
    };
    // When notifies by the modal send the request of update 
    this.notify = function(){
        // state has changed
        this.updateView();
    };
}

// Test
var modal = new Modal();
var consoleView = new View(modal);
var controller = new Controller(modal,consoleView);
consoleView.pressButton();
consoleView.pressButton("JS dominates the web world");
consoleView.pressButton("JQuery is a useful library of JS");