user1960364
user1960364

Reputation: 2001

JavaScript Design Pattern

I am working on a chat room application in JavaScript using websockets. However, aside from the small snippets of jQuery here and there, I have very little experience with JavaScript.

My question is, what design pattern should I use to make an object self contained and to be able to create multiple instances of it without interfering with other instances of the same object? Also, I need to know how I can store public object properties and access them from within event handlers when the 'this' keyword refers to something other than the current objects instance.

Code examples would be great!

Currently, I'm using the prototype design pattern and it seems to be working but isn't very elegant - to say the least... Especially with how I'm handling events, is there a better way?

I am currently doing something like:

function Room( args ) {
    this.container = $( '#room-' + args.id );
    this.container.find( '.someBtn' ).on( 'click', this.someEventHandler() );
}

Room.prototype.someEventHandler = function() {
    var self = this;

    return function( event ) {
        console.log( self, this, event );
    }
}

Upvotes: 3

Views: 405

Answers (2)

Esailija
Esailija

Reputation: 140230

I suggest you don't leave it to Room to figure out the element and use $.proxy

function Room( args ) {
    this.container = $( args.elem ); //elem can be selector, dom element, or another jQuery object
    this.container.find( '.someBtn' ).on( 'click', $.proxy( this.clicked, this) );
}

Room.prototype.clicked = function(event) {
    console.log( this, event.currentTarget );
}

In the clicked method this is the room instance abd event.currentTarget is the element the handler is attached on or the delegated target. See http://api.jquery.com/event.currentTarget/

I have a pending feature request for jQuery to make the above even cleaner http://bugs.jquery.com/ticket/12031

Upvotes: 0

Dziad Borowy
Dziad Borowy

Reputation: 12579

The prototype is good enough and it works great for the task you've described.

If you want more you can't escape from reading :-) There are many design patterns out there, and sometimes it's more a matter of preference because the differences are small.

Here's one of the best readings about patterns: JS Design Patterns

and another one about module patterns and requirejs: organising code using modules

Upvotes: 1

Related Questions