Creating a Preference
In this tutorial we're going to create a preference for use with the Creating a Command tutorial's /slap command. The pref will control what the /slap command slaps with.
How to Define Preferences
Like with commands, preferences are added using the following line:
client.prefManager.addPrefs(plugin.prefAry);
As before, the array plugin.prefAry defines the preferences to add, as has a very similar layout to the command array used for commands.
Each item in plugin.prefAry should be an array, with two items:
|
|
Item Type
|
Description
|
|
1
|
String
|
The preference name.
|
|
2
|
String, number, boolean, Array or function
|
The default value for the preference.
|
|
Using an Array or a function as the default value won't be covered here. The other three types simply set the default value for the preference. In our case, we're going to be doing a string preference, so the default value will be a string.
Our Preference's Definition
This should be very straight-forward, especially after the command definition in the previous tutorial. The preference will be called "slap.with" to allow for more slap-related preferences, and the default is "a small fish" as we used in the command tutorial. Thus we define the preference as:
plugin.prefAry = [ ["slap.with", "a small fish"] ]; client.prefManager.addPrefs(plugin.prefAry);
As before, this code needs to go inside the initPlugin routine.
Reading and Writing Our Preference
The Preference Manager provides us with a neat, "non-thinking" way to get and set any preference we care to.
// To get the value: var value = client.prefs["slap.with"]; // To set the value: client.prefs["slap.with"] = "a brick";
Couldn't be simpler, really. Now, let's use the preference...
Updating the Command Handler
Our current cmdSlap looks like this (unless you've gone an extended it already):
function cmdSlap(e) { dispatch("me slaps " + e.nickname + " about a bit with a small fish"); }
What we want is to use the pref "slap.with" for the final part of the message, so we need to change the dispatch line to read:
dispatch("me slaps " + e.nickname + " about a bit with " + client.prefs["slap.with"]);
That's it, and the Preference Manager does all the hard work of saving and loading the preference, as well as making sure to use the default if it's not set.
Changing the Preference
The preference may be set like any other, using the /pref command:
/pref slap.with a large brick
And reset to the default:
/pref slap.with -
Now that we've finished this tutorial, here's the full code for referrence.
Powered by the Content Parser System, copyright 2002 - 2010 James G. Ross.
|