Angela Costa
Angela Costa

Reputation: 1

combine multiple functions with same code in jquery

Yes, I have thoroughly searched google and did not find anything that suits my requirement.

The code i have so far is at the link below:

http://jsfiddle.net/ZKwTY/4/

There are multiple onchange events which call almost the same code, i would like to combine them maybe in a comma separated fashion to call it only once. something like this

   (on1Change, on2Change, on3Change): function () {
       this.loadData();
     }

is this possible??

Note: these functions are bound to the controls via a framework over which i do not have control, i need to create these functions and the framework would bind these to the respective controls

Upvotes: 0

Views: 77

Answers (3)

Ranjit Swain
Ranjit Swain

Reputation: 309

or you can create your object like this

var ol = {
on1Change: this.loadData,
on2Change: this.loadData,
on3Change: this.loadData,
on4Change: this.loadData,

loadData: function () {
    this.loadData1();
    this.loadData2();
},

loadData1: function () {
    alert('hi from loadData1');
},

loadData2: function () {
    alert('hi from loadData2');
}
};

Then if you want to do it once, then declare a object

var ol = {
    loadData: function () {
        this.loadData1();
        this.loadData2();
    },

    loadData1: function () {
        alert('hi from loadData1');
    },

    loadData2: function () {
        alert('hi from loadData2');
    }
};// end of object

ol.on1Change = ol.on2Change = ol.on3Change = ol.on4Change = ol.loadData;

add all propteries dynamically after object declaration

Upvotes: 1

Grundy
Grundy

Reputation: 13381

you can try somethig like this http://jsfiddle.net/s4VVY/ i.e. add methods after object create

[1,2,3,4,5].forEach(function(it){ol["on"+it+"Change"] = function(){this.loadData()}}) 

UPDATE
may be this help

var ol = (function(){
    var o = {
        loadData: function () {
            this.loadData1();
            this.loadData2();
        },

        loadData1: function () {
            alert('hi from loadData1');
        },

        loadData2: function () {
            alert('hi from loadData2');
        }
    }
    o.on1Change=o.on2Change=o.on3Change=o.on4Change=function(){ this.loadData();};

    return o;
})()

also you can make function bindFunc

function bindFunc(){
    var obj = arguments[0],
        handler = arguments[1],
        properties = Array.prototype.slice.call(arguments,2);

    for(var i in properties){
        obj[properties[i]] = handler;
    }
}

and call as

bindFunc(o,function(){this.loadData();},"on1Change","on2Change","on3Change","on4Change")

Upvotes: 0

Rituraj ratan
Rituraj ratan

Reputation: 10378

use bind()

$("selector").bind(on1Change, on2Change, on3Change): function () {
        this.loadData();
  }.....

Upvotes: 0

Related Questions