Question

I have page where users click an "add person" button. That pops up a modal loaded via ajax and displayed with jQuery UI Dialog. The popup contains a search form where the users selects a person to be added. When they hit 'ok' I would like the javascript on the page to retrieve the ID of the person selected and display it on the page that brought up the modal.

This is all fine and I can get it to work, but it's invariably ugly and I end up writing code in either my modal view or in my page view which requires a knowledge of the DOM in the other. For example, the modal could be aware that on the calling page there is a div#new-person and it could put the new person there. But that requires the modal to be aware of the base page.

Or I could pass along a javascript function from my application code to the modal, but that would require the modal to be aware of that function and call it explicitly. jQuery UI Dialog offers the ability to create buttons with onclick specified on the base page, but my modal is more complicated than that (I don't want those buttons to show up until a person has been selected) so I can't use them.

Was it helpful?

Solution

i have a Callbacks class that i pass events between Js clases

var Callbacks = {};
Callbacks.triggers = {};

Callbacks.addCallback = function( trigger, instance, method ){

    if( this.triggers[ trigger ] == undefined ){
        this.triggers[ trigger ] = Array( { obj:instance, action:method } );
    }else{
        this.triggers[ trigger ].push( { obj:instance, action:method } );
    };
};

Callbacks.fireCallback = function( trigger, param ){

    if( this.triggers[ trigger ] == undefined ){
        return;
    };

    for (var i=0; i < this.triggers[ trigger ].length; i++) {
        var listener = this.triggers[ trigger ][ i ];

        if( listener.action != undefined ){
            listener.obj[ listener.action ]( param );
        }
    };

};

Usage

/// some class to listen to a callback

function ListenClass(){

  this.build = function(){
    Callbacks.addCallback( 'myCallback', this, 'triggerMethod' );
  }

    this.triggerMethod = function( params ){
      alert( params );
    }

    this.build();

}

/// some class firing a callback
 function TriggerClass(){

  this.fire = function(){
  alert( 'fired' );
  Callbacks.fireCallback( 'myCallback', { value:'hey there this is a callback'} );
  }


}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top