0

I am trying to understand how chained function work and in particular how is it possible to pass the selected element to the chained functions.

Assuming that we have a chained function as follow:

var func = {};
func.remove= function() {
    $(this).remove();
}

How can I select an element by jQuery or JavaScript and pass it to the chained function as follow:

var elm = $("foo");
elm.func.remove();

OR

var elm2 = document.getElementById("foo");
elm2.func.remove();
cyrus-d
  • 749
  • 1
  • 12
  • 29
  • 1
    All a chained method is, is a function that returns an object. This allows the developer to simply call methods on that returned object. Your first example (`func,.remove`) is NOT a chainable method since it doesn't return anything. – Scott Marcus Mar 31 '16 at 15:59
  • See this: http://stackoverflow.com/questions/1768150/how-to-add-a-function-to-jquery – Peter B Mar 31 '16 at 16:01

1 Answers1

3

A chained function is a method that returns the object it is called on (so it can't return the element itself unless you extend the native DOM objects, which isn't recommended).

func isn't chained because it isn't a function at all. remove isn't chained before it doesn't return the object it belongs to.

If you want to do chained functions that work with an element, then you would need to define an object, defined chained methods on that object, and store the element as a property of that object.

For example:

function MyConstructor(element) {
    this._element = element;
}

MyConstructor.prototype.doA = function doA () {
    console.log(this._element);
    return this;
};

MyConstructor.prototype.doB = function doB () {
    element.style.display = "none";
    return this;
};

var example = new MyConstructor(document.getElementById('foo'));
example.doA().doB();
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335