YUI Dialog Buttons Scope

When calling a function to handle the click event for the YUI Dialog buttons, the scope of the function is always the dialog instance itself. This is not a problem in most situations, but when creating a custom YUI widgets, use the object literal option to handle the event rather than just calling a function. Otherwise, you will run into scope issues.

I usually create a  YUI Dialog in a fairly standard way:

?View Code JAVASCRIPT
var dlgContainer = new Dialog("dlgContainer", {
     width: "75px",
     buttons: [ { text:"Submit", handler: handleSubmit, isDefault:true },
	        { text:"Cancel", handler: handleCancel } ],
     draggable:false,
     close:true,
     fixedcenter : true,
     constraintoviewport : true,
     modal: true
});

And then the handlers:

var handleSubmit = function() {

};

var handleCancel = function() {

};

This works fine. Placing this same code in the init method of a YUI Widget:

?View Code JAVASCRIPT
...
init:function(oConfig) {
   this.container = new Dialog(this.container, {
        width:"175px",
	buttons: [{ text:"Submit", handler: this.handleSubmit, isDefault:true },
	          { text:"Cancel", handler: this.handleCancel } ],
	draggable:false,
	close:true
        ...
   });
},
handleSubmit:function() {
     if (this.validate()) {
 
     }
},
handleCancel:function() {
     this.cancel();
     ...
},
validate:function() {
     ...
}
...

The handleSubmit method calls this.validate (a method of the widget). Because the scope of handleSubmit is the dialog instance, the validate method of the widget will not fire (out of scope). In order to change the scope of the dialog buttons click handler, you have to use an object literal:

?View Code JAVASCRIPT
...
buttons : [ { text:"Submit", handler: {fn:this.handleSubmit, obj: this, scope: this}, isDefault:true },
	      { text:"Cancel", handler: this.handleCancel } ]
...

The object literal for the YUI Dialog buttons handler takes the format:

{
fn: Function, // The handler to call when the event fires.
obj: Object, // An object to pass back to the handler.
scope: Object // The object to use for the scope of the handler.
}

In my example,

{fn: this.handleSubmit, // a method of the widget

obj: this,  //I’m passing the widget as the object

scope: this //I want the widget to be the scope of the handler

}

I hope this was helpful.

Be Sociable, Share!

Checkout My New Site - T-shirts For Geeks