Seperating View & Controller logic in Javascript objects

Im wanting to seperate the DOM manipulation and interatcion (jQuery) lets call this the VIEW from my client side application logic (socket.io) lets call this the controller. The communication needs to be two way:

  • VIEW to CONTROLLER when user interacts with the DOM e.g. clicks a button
  • CONTROLLER to VIEW when server sends an update to be displayed in DOM e.g. new chat message

I'm having trouble communicating between these two JavaScript objects. How do i communicate between the two in a efficient way?? simple example below.

// CONTROLLER LOGIC (socket.io stuff)
function socketController() {}

socketController.prototype = {

    constructor: function() {

        // define socket listners
    this.socket.on('chatMessage', this.chatUpdate.bind(this));
    }

    chatUpdate: function(data) {

        // somehow call a "render" function on the "view" object
        // this.view.renderChatDOM(data.username, data.message);
    }
}

// VIEW LOGIC (jQuery stuff)
function jqueryView() {}

jqueryView.prototype = {

    onDOMReady: function() {

        // bind event handlers
        $('#send-message').bind('click', this.sendMessage.bind(this));          
    }

    sendMessage: function(event) {

            // manipulate DOM
        var $messageNode = $('#message-input'),
                $buttonNode = $('#send-message'),
                message = $messageNode.val();

            $messageNode.val(''); // clear input

            // somehow call the socketController and send data
            // this.socketController.chatSend(message);
    }
}

Why dont you have a look at a DOM manipulation library that provides two way data binding from the view to controller (or viewmodel). Then you wont have to manage the manual updates, but just change your client side model (or client view) where the framework will take care of keeping layers in sync. http://knockoutjs.com might be a good place to have a look at.

So in the end Hasith was right. I was indeed looking for a MVC framework in javascript. I have decided to go with backbone.js as it is the least intrusive as far as size, learning curve and resources are concerned.

this solves my problem of seperating application logic (MODEL) from DOM manipulation and presentation (VIEW).

Go backbone.js!!