Moon
Moon

Reputation: 22565

Is this MVC in javascript?

Despite I have been using MVC in PHP many times, I found out that it is quite different in Javascript. I'm reading MVC in Javascript over the web, but many of them have a different implementation. I came up with a simple MVC, but I think this is not correct. Is this acceptable or completely wrong?

var AppView = View.extend({

    init: function()
    {

        // listen to Model changes
        this.listen("counterChanged", $.proxy( this.updateCounter, this ));

        // assign click event; call controller method
        this.container.find("#increase").click( this.callback( this.Controller, "increase" ));
        this.container.find("#decrease").click( this.callback( this.Controller, "decrease" ));
    },


    updateCounter: function( evtData )
    {
        this.container.find("#counter").html( evtData.newValue );
    }

});

var AppController = Controller.extend({

    increase: function()
    {
        this.Model.update("counter", this.Model.get('counter') + 1 );

    },

    decrease: function()
    {
        this.Model.update("counter", this.Model.get('counter') - 1 );

    }

});


var AppModel = Model.extend({


    onUpdate_counter: function( newValue )
    {
        this.fireEvent("counterChanged",{
            newValue: newValue
        })
    }

});




var App = {}

$(document).ready(function(){

    App.Model = new AppModel({
        counter: 0
    });
    App.Controller = new AppController( App.Model );
    App.View = new AppView("#app", App.Controller );    

    App.Model.setView( App.View );

});

HTML:

<div id='app'>

    <div id='counter'>0</div>

    <a id='increase'>Increae</a>
    <a id='decrease'>Decrease</a>

</div>

View listens to changes in the model and assigns events to html anchors. View calls the controller when the anchors are clicked then controller updates the model.

Upvotes: 2

Views: 328

Answers (1)

clyfe
clyfe

Reputation: 23770

This is classic 1979-type MVC:

  • controller updates models
  • models update views via listeners

PHP/Rails (web request/response in general) is a slightly different type of MVC (constricted by the request/response nature of the web):

  • controllers update models
  • controllers take data from models and send it to views

In both types, view events trigger controller actions.

Upvotes: 2

Related Questions