user2026121 user2026121 - 20 days ago 8
jQuery Question

How to create methods with a loop in jquery/javascript

I'm having problems trying to register some methods I've created in a loop inside an object.

what I'm having is this:

var scriptList = {
components : [
'all'
],
modules : [
'one',
'two',
'three'
]
}

function interface() {
var scope = this;

jQuery.each(scriptList, function(key, value) {
jQuery.each(value, function (index, name) {
var hookValue = 'hook_'+name;

scope.name = function(){
window[hookValue] = jQuery('.js-'+name);
loadAndUse(window[hookValue],key+'/'+name);
}

if(key === 'modules'){
scope.name();
}
});
});
}

var ui = new interface();


It's working and do its job, but I want to be able to reach every method I've created through the loop in this way:
console.log(ui.one());


And I don't how to do something like that since if I do this:

function interface() {
var scope = this;

scope.one = function(){ console.log('one'); }
scope.two = function(){ console.log('two'); }
scope.three = function(){ console.log('three'); }
}


then I can access through
console.log(ui.one());
with no problem...

What am I missing? Is there some way I don't know on registering the method when you iterate them?

Answer

scope.name refers the the name property on scope. If you want to access a property based on a string value, you need to use square bracket notation:

scope[name] = function(){
    window[hookValue] = jQuery('.js-'+name);
    loadAndUse(window[hookValue],key+'/'+name);
}
Comments