EasyBB
EasyBB

Reputation: 6574

Can we run certain javascript in an object?

I am new at JavaScript objects and wondering if we could run JavaScript in an Object? This is what I want to do-

$('.element').click(function () {
    var data = $(this).attr('data-home');
    if (data !== undefined) {
        var jsRun = {
            a: $('.more').show(),
            b: $('.div').show(),
            c: window.location = "www.url.com",
            d: location.reload()
        };
    }
    return jsRun[data];
});

I wrote return jsRun because I'm not quite sure what to do if this is allowed and how to make it run the code that I specified. Any suggestions would help thanks

Upvotes: 1

Views: 89

Answers (4)

user1726343
user1726343

Reputation:

Enclose all of those in functions, after which they can be invoked as methods of the object.

$('.element').click(function () {
    var data = $(this).attr('data-home'),
        jsRun; //your variable declaration is hoisted to here anyway
    if (data !== undefined) {
        jsRun = {
            a: function(){
               $('.more').show();
            },
            ...
        };
        return jsRun[data]();
    }
});

The result, assuming data is "a", is that $('.more') is shown. I've moved the invocation inside the conditional block, since I'm assuming you only want this to happen if data has a value.

Upvotes: 5

adeneo
adeneo

Reputation: 318302

Use a switch :

$('.element').on('click', function() {
    switch ( $(this).data('home') ) {
       case 'a': $('.more').show();
         break;
       case 'b': $('.div').show();
         break;
       case 'c':  window.location = "www.url.com";
         break;
       case 'd':  location.reload();
         break;
       default:
                  goNuts(); // do something if none of the above 
    }
});

Upvotes: 4

Gabriel Petrovay
Gabriel Petrovay

Reputation: 21934

You are not running this code inside the object.

You are running it before the object creation. Anything that these expressions will return will be set into the keys where you placed the expression.

Be aware that any expression returns something, at least: undefined

Upvotes: 0

Dave
Dave

Reputation: 46339

You need to use functions;

a: function(){$('more').show();}

Then call

jsRun[data]();

(Note the brackets)

Upvotes: 2

Related Questions