Confirmation dialog callbacks for sub-objects

I created a user confirmation dialog box that can execute a callback and the parameters that will be executed if the user confirms the action.

function Confirm( text, callback, params ) { var html = '\ <div class="modal-header clearfix">\ <h1 class="title">Confirm</h1>\ </div>\ <div class="modal-content">\ <p>' + ( text != null ? text : 'Are you sure you want to do this?' ) + '</p>\ </div>\ <div class="modal-footer clearfix">\ <div class="float-right">\ <div class="btn-group">\ <button class="btn ajax-modal-close">Cancel</button>\ </div>\ <div class="btn-group">\ <button class="btn important confirm">Ok</button>\ </div>\ </div>\ </div>\ '; Modal.dataModal(html, 640, 320); // Custom Modal framework $('.confirm').click(function(e){ e.preventDefault(); if(callback) { if(params) { callback = callback.replace(/window./gi, ''); // remove window. prefix so we can call the callback on the window object below if(Array.isArray(params)) { window[callback].apply(window, params); } else { window[callback].call(window, params); } } else { window[callback](); } } Modal.closeModal( $('.Modal').last() ); // Custom Modal framework }); } 

And an example of calling this function would be:

Confirm('Are you sure? All your data will be lost!', 'window.location.replace', '../');

So, if the user confirms this action, he will redirect them to the previous page.

However, this does not work for sub-objects, such as replace , which belongs to location , not window . To call this, I will need to call it the following: window['location']['replace'].call(..

How can I handle sub-objects? When they are passed as strings.

As if I were calling it directly in the width of the console: window['location']['replace'].call(window, '../'); it throws an error: Illegal invocation .

0
source share
2 answers

To get the correct function and context, you can do something like this:

 var func_parts = callback.split("."), context = callback = window; $.each( func_parts, function(index){ if( this != "window" ) callback = callback[this]; if( index == func_parts.length - 2 ) context = callback; }); 

then use it as follows:

 if (callback) { if (params) { if (Array.isArray(params)) { callback.apply(context, params); } else { callback.call(context, params); } } else { callback(); } } 
+1
source

You need to track the context, moving along the path of the object. Something like the code below will work, but as mentioned in the comment, you can use something like object-path for a general solution.

 var context = window, split = callback.split('.'), foo = split.shift(); if(foo == 'window') foo = split.shift(); while(split.length) { context = context[foo]; foo = split.shift(); } 

at the end of this you will have the correct context and foo to execute

 context[foo].call(context, params); 
+1
source

All Articles