Question

Diving into JS prototypes I am trying to pipe through a parameter to an already existing function. This is the result.

chardinJs.prototype.start = function (txtTag) {
  this.infoTag = txtTag;
  var el, _i, _len, _ref;

  if (this._overlay_visible()) {
    return false;
  }
  this._add_overlay_layer();
  _ref = this.$el.find('*[' + infoTag + ']:visible');
  for (_i = 0, _len = _ref.length; _i < _len; _i++) {
    el = _ref[_i];
    this._show_element(el);
  }
  return this.$el.trigger('chardinJs:start');
};

Originally there was no 'txtTag' as a parameter and the function worked fine, but once I added it, I am getting an error "$(...).chardinJs.start is not a function". What gives?

PS: I am trying to use the function like this:

$('form').chardinJs.start('data-info');

Before modifications I was using the function like so:

$('form').chardinJs('start');
Was it helpful?

Solution

You added start as a function on the prototype, but you are trying to access it from the constructor function, rather than from an instance. To call it via the prototype, you'd have to use the new keyword to create an instance:

(new ($('form').chardinJs())).start('data-info');

I'm not sure if that would even work. To call it the way you want to, you'd have to make start a property of chardinJs:

chardinJs.start = function (txtTag) {
    ...

But, that woudn't work either, because you'd lose your context.

Really, to accomplish what you are trying to do, you'd have to add those functions to the jQuery object when you call chardinJs:

$.fn.chardinJs = function () {
    // your existing implementation
    this.start = chardinJsStart;  // reference your start function
    return this;
};

Then you could do:

$('form').chardinJs().start('data-info');

One other option would be to keep it the way you have it working already, but pass the method parameter after the method name:

$('form').chardinJs('start', 'data-info');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top