JavaScript Help

I'm afraid that today I can lose my marble, because I do not know how to do what I want. I want to create a special invitation that I can call from any of my other JavaScript functions. I don’t know how to get this job, although it seems to me that I did it a hundred times.

Here is an example

var modal = function() {

    var prompt = function(msg) {
        // custom prompt builder here... let return hard coded for example sake
        return true;
    };

}();

var items = function() {
    var init = function() {

        $('.delete').click(function() {
            var confirm = modal.prompt('Are you sure you wanna delete that pal?');
        });

    };    


    $(document).ready(init);    
}();

What I want to do is call the prompt modal method and get the return value based on user input. Now I can do it, but I'm having problems calling the internal method. I want to group them together because I will probably also have my own modal alert().

Please do not offer built-in JavaScript OK / Cancel, as I have to follow this custom.

Many thanks!

+3
4

modal.prompt, , , modal:

var modal = (function() {
    // various private fields & methods here
    ...
    // the public interface
    var self = {
        prompt: function(msg) {
            // custom prompt builder here... let return hard coded for example sake
            return true;
        }
    };
    return self;
})();
+4

prompt ​​ modal, , :

var modal = (function() {
  var privateMethod1 = function () {/*...*/},
      privateVar = 'foo';

  function privateMethod2() {
    //...
  }

  return { // public members
    prompt: function (msg) {
      // custom prompt builder here... let return hard coded for example sake
      return true;
    }
  };
})();

:

, , prompt .

, , JavaScript OK/ window.prompt , .

var modal = (function() {
    return {
      prompt: function(msg, okCallback, cancelCallback) {
        // ...

        $('#okButton').click(function () {
          // internal actions here, like closing the dialog, cleanup, etc...
          okCallback(); // execute the ok callback
        });

        $('#cancelButton').click(function () {
          // ...
          cancelCallback(); // execute the cancel callback
        });
      }
    };
})();
+3

I highly recommend anyone who is going to write javascript code to read and understand this http://www.jibbering.com/faq/faq_notes/closures.html .

This is critical.

+2
source

You tried:

var modal = {
    prompt : function(msg) {
           return true;
         }
};

and then you can do it like:

modal.prompt();
0
source

Source: https://habr.com/ru/post/1730821/


All Articles