Sadaf Siddiqui Sadaf Siddiqui - 6 months ago 20
Javascript Question

calling chain method in javascript

I am using the following code but it is constantly giving me errors :


TypeError: container("accounts").atPosition("#left-top") is undefined


the code is :

function container(name, position) {
return {
pos: null,
atPosition: function(position) {

$(position).html(this.newContainer());
//$(position+" .main").html("yes");
this.pos = position;
},
populateData: function(rdata) {
$("#left-top .main").html(rdata);
},
newContainer: function() {
//alert(this.pos);
return '<h3>' + name.toTitleCase() + '</h3>\
<div class="main">\
</div>';
}
};
}

container('accounts').atPosition('#left-top').populateData("yahoo!!!!");​


Why am I receiving this error and how can I fix it?

Answer

You supposed to return this from functions for chaining. By default function return undefined (if you dont use new operator) . by returning this from function which don't have any thing to return will help in chaining.

function container(name, position) {
    return {
        pos: null,
        atPosition: function(position) {
            $(position).html(this.newContainer());
            //$(position+" .main").html("yes");
            this.pos = position;

            return this;
        },
        populateData: function(rdata) {
            $("#left-top .main").html(rdata);
            return this;
        },
        newContainer: function() {
            //alert(this.pos);
            return '<h3>' + name.toTitleCase() + '</h3>\
                <div class="main">\
                </div>';
        }
    };
}​
Comments