samfrances
samfrances

Reputation: 3705

Where does the code go to link View to Model and View to Controller?

I think I have a basic understanding of the idea of Model-View-Controller. I've used it in the context of server-side development, but client-side seems to be a bit different. I'm trying to write applications without a framework to get a better understanding.

My understanding of javascript MVC applications

However, what I'm not sure about is where the code goes to set up these links.

It seems to me that these connections would be in the initialiser function of either the View or the Controller.

A very simple, toy example:

function View(model, controller) {

    model.addSubscriber(this.render);

    // code to set up DOM elements etc.

    this.button1 = document.getElementById("button1");

    this.button1.addEventListender("click", function() {
        controller.buttonhandler();
    })
}

View.prototype.render = function() {
    //
}

var view = new View(model, controller)

Or alternatively:

function Controller(model, view) {

    model.addSubscriber(view.render);

    view.button1.addEventListender("click", function() {
        this.buttonhandler();
    })

}

Controller.prototype.buttonhandler = function() {
    //
}

var controller = new Controller(model, view);

Is either one of these the "right" way to do MVC in client-side javascript? If not, are there advantages of one way over the other? Or am I just confusing the whole entire issue?

Upvotes: 1

Views: 305

Answers (1)

Alex Netkachov
Alex Netkachov

Reputation: 13562

You can look at my article about the subject:

I will be happy if you like it.

Upvotes: 1

Related Questions