views:

216

answers:

1

I am using the jQuery token input plugin and would like change its behavior when a token is added.

I added an "onAddToken" callback to the original code so I can see when a token is added to the input box, but I'm not sure how to alter tokenInput's URL from "url/to/call" to a new URL, "new/url/to/call".

this, $this, and $(this) do not seem to work. Any suggestions?

$("#input").tokenInput("/url/to/call", {
        noResultsText: "No results yet. Type some more...",
        searchingText: "Searching...",
        onAddToken: function(args) {
            // alter tokenInput itself to use "new/url/to/call" instead of 
            // the original "url/to/call/"
    }
 });
+2  A: 

The problem is that any function arguments that are native types (numbers, strings, etc...) that they will be passed by value (copied) to the called function. You want to have an argument that is passed by reference, and the only way to do this in javascript is to pass an object.

At the callsite (in the plugin) call the function something like this:

config.onAddToken({url: myUrlVar});

then in your callback you can change the value of the url property of the passed-in object.

$("#input").tokenInput("/url/to/call", {
        noResultsText: "No results yet. Type some more...",
        searchingText: "Searching...",
        onAddToken: function(oUrl) {
            oUrl.url = "mynew/url";
        }
});

This is useful in cases where you want to pass multiple values by reference, in your case however you may want to just have your callback return whatever url value you want the plugin to use, this puts some onus on the developer to know to do that but it may be easier.

At the callsite:

myUrlVar = config.onAddToken(myUrlVar);

And the callback:

$("#input").tokenInput("/url/to/call", {
        noResultsText: "No results yet. Type some more...",
        searchingText: "Searching...",
        onAddToken: function(oUrl) {
            return "mynew/url";
        }
});

Or you could default to just use the value if there was nothing returned from the callback:

var newUrlVar = config.onAddToken(myUrlVar);
if(newUrlVar)
    myUrlVar = newUrlVar;

If the callback function doesn't have a return in it then it's value should be null.

joshperry
Thank you very much for your detailed answer. I went with your first option, which gave me maximum flexibility, and it worked perfectly. I can even pass the entire settings of the plugin back as an object to be modified. Again, excellent response - thanks!
Wraith