haunted85
haunted85

Reputation: 1671

jQuery and chaining issue

I'm a jQuery rookie and maybe I'm about to ask a very basic question, but I'm really struggling while figuring out why jQuery chaining doesn't work in my case.

var container = $('#container'),
items = container.find('ul.items'),
moreItems = items.children('li.moreItems');

var config = {
container : container,
items : items,
moreItems : moreItems
}

var app = myApp(config);

function MyApp(config) {
this.container = config.container;
this.items = config.items;
this.moreItems = config.moreItems;
this.current = 0;
}

MyApp.prototype.myUsefulFunction() {
this.moreItems[this.current].fadeIn();
}

Let's suppose I have a div#container filled with ul elements that have more than one li each. I'd like to access to the n-th li and fade the element in, but the console throws me back an error, stating fadeIn has no such method. Can you please help me sort it out?

Upvotes: 2

Views: 256

Answers (3)

charlietfl
charlietfl

Reputation: 171698

To make a jQuery method for chaining you need to extend jQuery.fn

$.fn.myUsefulFunction=function() {
    return this.each(function(){
        $(this).fadeIn();

    })
}

You can now use this as you would any other jQuery method

   $(selector).myUsefulFunction()

Upvotes: 1

Didier Ghys
Didier Ghys

Reputation: 30676

jQuery returns a jquery object, which is a sort of array containing DOMELements.

When you do: this.moreItems[this.current] you actually extract the DOMElement from the jquery array --> you have to turn it into a jquery object to be able to call fadeIn() !

$(this.moreItems[this.current]).fadeIn();

You can also use .eq(index) to filter the matched set to the only element corresponding to the index:

this.moreItems.eq(this.current).fadeIn();

DEMO


Apart from that, the piece of code you show in your question has several syntax errors:

  1. To add a function to the prototype, you should do:

    MyApp.prototype.myUsefulFunction = function() {}
    

    and not MyApp.prototype.myUsefulFunction() {}

  2. Use the new operator to return a new instance of MyApp

    var app = new MyApp(config); // also spelling mistake: myApp != MyApp !!
    

Upvotes: 5

Anber
Anber

Reputation: 319

Off-topic:

  1. For create instance of class you need use new:

    var app = new myApp(config);

  2. myApp and MyApp is a different variables.

Upvotes: 0

Related Questions