如何避免将参数传递给每个函数,但仍然可以在函数内访问它

时间:2017-09-14 02:44:04

标签: javascript jquery

当我单击按钮时,我打开一个Jquery对话框并创建一个CustomClass对象。我在不同的功能中需要这个对象。有没有办法避免将其传递给每个函数但仍然可以在函数内访问它?

注意:我使用相同的代码通过不同的点击事件打开多个对话框。

JS小提琴链接https://jsfiddle.net/gwphxssq/1/

HTML

<div class='btn1'>Button1</div>
<div class='btn2'>Button2</div>
<p class='plain-text'> Two dialog's open, one behind the other. Please drag the top dialog to see the other dialog below.
</p>

JS:

var Test = Test || {};
Test = {
  CustomClass: function(fnSave) {
    return {
      dialogElem: null,
      saveBtn: null,
      fnSave: fnSave
    }
  },
  Cache: function(obj, dialogElem) {
    obj.dialogElem = $(dialogElem);
    obj.saveBtn = $(dialogElem).find('.btnSave');
  },
  OpenDialog: function(option) {
    var that = this;
    var dynamicElem = '<div>Dialog' +
      '<input type="button" class="btnSave" value="Save"/>' + '</div>';

    var obj = new that.CustomClass(option);

    $(dynamicElem).dialog({
      open: function(event, ui) {
        that.Cache(obj, this);
      }
    });

    //obj is being passed to different functions. How can I avoid passing  it to each function but still have access to the obj in each of the functions below?

    that.BindEvents(obj);
    that.SampleFunc1(obj);
    that.SampleFunc2(obj);
  },

  BindEvents: function(obj) {
    obj.saveBtn.on('click', function() {
      obj.fnSave();
    });
  },
  SampleFunc1: function(obj) {
    //Need the obj here too
    //Some code
  },

    SampleFunc2: function(obj) {
    //Need the obj here too
    //Some code
  }
}


//Click Event for Button 1
$('.btn1').on('click', function() {

  Test.OpenDialog(function() {
    alert('First Dialog');
  });
});

//Click Event for Button 2
$('.btn2').on('click', function() {

  Test.OpenDialog(function() {
    alert('Second Dialog');
  });
});

CSS:

.btn1,
.btn2 {
  background-color: grey;
  width: 200px;
  height: 20px;
  text-align: center;
  padding: 3px;
  margin-bottom: 5px;
  display: inline-block;
}

.plain-text {
  color: red;
}

.btnSave {
  float: right;
  width: 80px;
  height: 30px;
}

1 个答案:

答案 0 :(得分:0)

你可以做一个创建新函数的工厂,这些函数在它们的闭包中有对象。例如:

OpenDialog: function (option) {
    var that = this;
    var dynamicElem = '<div>Dialog' +
       '<input type="button" class="btnSave" value="Save"/>' + '</div>';
    var obj = new that.CustomClass(option);

    var fxns = that.createFxns(obj);

    fxns.bindEvents();
    fxns.sampleFunc1();
    fxns.sampleFunc2();
},
createFxns: function(obj) {
    return {
        bindEvents: function () {
            obj.on('click', function () {
               obj.fnSave();
            }
        },
        sampleFunc1: function () {},
        sampleFunc2: function () {}
    }
}

虽然我没有看到你从这种模式中获得太多。这样做的主要好处是,您可以将这些函数传递给其他代码,并使对象已经“烘焙”。这样,另一段代码甚至不需要知道obj存在。在你的情况下,你只是马上打电话给你,你的班级显然需要知道obj的存在。