Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 );
    }
}
like image 426
user1960364 Avatar asked Dec 08 '25 06:12

user1960364


1 Answers

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

like image 147
Dziad Borowy Avatar answered Dec 09 '25 19:12

Dziad Borowy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!