Skip to Content
๐ŸŽฒ Welcome to RandBox - Powerful JavaScript Random Data Generation Library! Learn More

mixin

// usage randBox.mixin(<Object>)

Mixins are a very powerful way to extend RandBox to fit the needs of your specific application.

First, if you are thinking of using a mixin for RandBox, please consider first whether your use is something from which others may benefit. If so, please submit a pull requestย  rather than using a mixin!

Spread the love and give everyone the benefit of your awesome generator :)

Now, that said, there are bound to be times when you want to generate something random that is specific to your application but not widely applicable. Enter mixins!

RandBox mixins allow you to add one-off methods to RandBox which you can use later.

For example, letโ€™s say I have a user object which consists of first, last, and email.

var user = { first: 'John', last: 'Smith', email: 'john@aol.com' };

Letโ€™s say I want to be able to randomly generate these user objects.

This is not the type of thing which would be widely applicable as itโ€™s specific to my application so itโ€™s perfect for a mixin!

To create a mixin, build an object whose keys are the names of the methods, and whose values are the functions to be called.

Note: Within each function, you will have access to randBox itself!

For example, to create a user mixin:

randBox.mixin({ 'user': function() { return { first: randBox.first(), last: randBox.last(), email: randBox.email() }; } }); // Then you can call your mixin randBox.user(); => {first: 'Eli', last: 'Benson', email: 'gembibuj@dugesan.com'}

Mixins can even include other mixins!

For example, to โ€œextendโ€ the user object:

randBox.mixin({ 'user': function () { return { first: randBox.first(), last: randBox.last(), email: randBox.email() }; }, 'social_user': function () { var user = randBox.user(); user.network = randBox.pick(['facebook', 'twitter']); return user; } });

So we have a second mixin here, social_user which is using the user mixin and adding to it! Note, these mixins can be defined in any order on the object if both declared at once.

Last updated on: