javascript - how to pass parameters in an function object literal -


i pass integers min , max parameters function return random number use in function. i'm new javascript , i'm using object literal pattern. i'm getting error "this.randomgenerator not function". how can return number randomgenerator to used in interaction?

bindevents: function() {      $('#left').on("click", this.interaction);  },  interaction: function() {     var selector = this.randomgenerator(0, 3);     var $columns = $('#left').find('div[col]');       $columns.children().removeclass('show');     $columns.eq(selector).children().addclass('show');  },  randomgenerator: function(min, max) {      var last,                value,               count = 0,           getr = function () { return math.floor(math.random() * (max - min)) + min; };        return function () {          var random;          if (count && value !== last) {             --count;              return last = value;          }          random = getr();          while (random === last) {               value = random;               ++count;              random = getr();          }          return last = random;      };  },

the issue because this within click handler refers element clicked on, not object contains randomgenerator() function.

to fix problem can keep reference this in variable, before using $.proxy() (or bind()) set scope randomgenerator() function should run under. try this:

var obj = {    bindevents: function() {      var _this = this;      $('#left').on("click", $.proxy(_this.interaction, _this));        // note can use native bind() method, if preferred:      // $('#left').on("click", _this.interaction.bind(_this));    },    interaction: function() {      var selector = this.randomgenerator(0, 3);      console.log(selector()); // testing...            var $columns = $('#left').find('div[col]');        $columns.children().removeclass('show');      $columns.eq(selector).children().addclass('show');    },    randomgenerator: function(min, max) {      var last,        value,        count = 0,        getr = function() {          return math.floor(math.random() * (max - min)) + min;        };        return function() {        var random;        if (count && value !== last) {          --count;          return last = value;        }        random = getr();        while (random === last) {          value = random;          ++count;          random = getr();        }        return last = random;      };    }  }    obj.bindevents();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div id="left">click me</div>


Comments

Popular posts from this blog

What is happening when Matlab is starting a "parallel pool"? -

angular - DownloadURL return null in below code -

php - Cannot override Laravel Spark authentication with own implementation -