Pregunta

I want method chaining to work, but it seems i'm not getting some concepts.

This:

$(".list").activeJS()

first has to use jQuery to get a HTMLElement nodelist and then it has to call the activeJS() function passing the nodelist.

var activeJS = function(item){

    alert(item) //nodelist


}

Now i get a TypeError: $(...).activeJS is not a function error in my console.

Thx,

¿Fue útil?

Solución

If you want to create a function callable from a jQuery object, you have to add it to the jQuery prototype object:

jQuery.fn.activeJS = function(item) {
  // ... whatever
};

Otros consejos

When a function is added to jQuery (which allows for chaining) it is referred to as a plugin and several things must be taken into consideration. For example, is your function itself chainable? Will your function work on a single element or multiple? I would recommend that you research jQuery plugins and build your function as a plugin in jQuery.

Here is an excellent tutorial on building a jQuery plugin that covers concepts such as chaining, passing properties and calling different plugin functions. Take a look at the article and determine if your function truly needs to be a plugin.

It may be better to simply pass jQuery and the selected elements as arguments to your function instead of chaining.

Take a look at this example:

var obj = {
    fn: function(){
        console.log("fn method");
        return this;
    },
    abc: function(){
        console.log("abc method");
        return this;
    },
    oneMore: function(){
        console.log("one more method");
        return this;
    }
};

Here chaining is provided by returning reference to obj Object. Simply, every time you call a method on that object, you are returning that object - and you can continue calling its methods. This is basic chaining pattern that you can find in jQuery also - slightly modified but the idea is same. Thanks to dynamic nature of javascript we can do this kind of things. Chaining allows coupling of related methods that are connected by common object. This pattern has its roots in functional programming, and javascript is heavily influenced by functional languages (mostly scheme). But too much chaining can lead to unreadable code as can be seen in lot of jQuery examples.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top