Skip to content Skip to sidebar Skip to footer

Jquery Plugin Return This.each And Add Function Property To Each Object?

Is it possible to create a jQuery plugin that returns this.each for multiple matches allowing me to add a function property to each object within the each loop? I want to call thi

Solution 1:

Minor change: just place getMyValue on 'this' and not on $(this) and access it by

$("input.coolStuff").first()[0].getMyValue()

Solution 2:

You can utilize .data() to store and call a function at an element; Function.prototype.bind() to set this to $(this) within .each() at getMyValue

$(function() {
  (function($) {
    $.fn.roflcopter = function(options) {
      returnthis.each(function() {
        $(this).addClass("lol");
        functiongetMyValue(e) {
          returnreturnMyFilteredValue(this);
        };
        $(this).data().getMyValue = getMyValue.bind($(this));
      });

      functionreturnMyFilteredValue(elem) {
        return elem.val(function(index, val) {
          return val.replace("cat", "dog");
        })
      }

    };
  }(jQuery));

  $("input.coolStuff").roflcopter();
  var value = $("input.coolStuff").first().data().getMyValue();
  console.log(value, value.val())
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><inputclass="coolStuff"value="cat" /><inputclass="coolStuff"value="cat" />

Post a Comment for "Jquery Plugin Return This.each And Add Function Property To Each Object?"