帮助JavaScript范围

时间:2010-02-01 05:42:22

标签: javascript jquery scope

我担心今天可能会失去我的弹珠,因为我不知道该怎么做我想做的事。我想要一个自定义提示,我可以从任何其他JavaScript函数调用。我不知道怎么做这项工作,即使它感觉就像我已经做了一百次。

这是一个例子

var modal = function() {

    var prompt = function(msg) {
        // custom prompt builder here... let's return hard coded for example's 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);    
}();

我希望能够做的是调用模态的提示方法,并根据用户输入获取返回值。现在,我可以这样做,但是我在调​​用内部方法时遇到了问题。我想将这些组合在一起,因为我可能也会有一个自定义模式alert()

请不要建议内置JavaScript确定/取消,因为我必须执行此自定义。

非常感谢!

4 个答案:

答案 0 :(得分: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's return hard coded for example's sake
            return true;
        }
    };
    return self;
})();

答案 1 :(得分:3)

对于您的第一个问题,prompt函数在modal对象中被声明为变量,您无法访问它,因为您实际上并未公开公开它:

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

  function privateMethod2() {
    //...
  }

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

现在出现以下问题:

  

我希望能够做的是调用模态的提示方法,并根据用户输入获取返回值。

用户输入是异步操作,我建议你使用基于回调的模型,内置的JavaScript OK / Cancel 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
        });
      }
    };
})();

答案 2 :(得分:2)

我强烈建议任何习惯于编写javascript代码的人阅读并理解http://www.jibbering.com/faq/faq_notes/closures.html

这非常重要。

答案 3 :(得分:0)

你试过了吗?

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

然后你可以像:

modal.prompt();
相关问题