Viji
Viji

Reputation: 15

How to create a widget instance in jQuery

Consider I have two widgets.

$.widget( "custom.car", {
    options: {
        name: ''
    },
    _create: function() {
        this.options.name = 'car'
    },
    random: function( event ) {
        console.log(this.options.name);
    },
    clear: function() { console.log('Clear'); }
});

$.widget( "custom.bike", {
    options: {
        name: ''
    },
    _create: function() {
        this.options.name = 'bike'
    },
    random: function( event ) {
        console.log(this.options.name);
    },
    clear: function() { console.log('Clear'); }
});

isCar and isBike is based on user input.

if(isCar) {
   $( "div" ).car();
   $( "div" ).car('random');
} else if(isBike) {
   $( "div" ).bike();
   $( "div" ).bike('random');
}

If I call the random method in some where place I'll write the if condition. If any possible solution to avoid the if condition or any other solution.

Note: My question is correct or not?

Upvotes: 0

Views: 382

Answers (2)

jriver27
jriver27

Reputation: 880

There is a lot of information missing from your post but here is a way to avoid an "if else" statement.

<form id="selection">
  <input id="car-radio" type="radio" value="car" checked> Car
  <input id="bike-radio" type="radio" value="bike"> Bike
</form>


<script type="text/javascript">

    var carFunc = function() {
        isCar = true;
        isBike = false;

        $( "div" ).car();
        $( "div" ).car('random');
    }

    var bikeFunc = function() {
       isCar = false;
       isBike = true;

       $( "div" ).bike();
       $( "div" ).bike('random');
    }

    $("#selection").on('click', '#car-radio', carFunc);
    $("#selection").on('click', '#bike-radio', bikeFunc);
</script>

Upvotes: 0

Titus
Titus

Reputation: 22484

Not really, you'll have to decide which method you want to call so you'll have to use an if...else if construct or at least a ternary operator.

Here is an example that reduces the number of statements:

var fName = isCar ? "car" : "bike";
$( "div" )[fName]();
$( "div" )[fName]('random');

In this example I assume that if isCar is false isBike is true which is not exactly like your example.

Upvotes: 0

Related Questions