开发者

jQuery Plugin: Using callback to alter plugin behavior

开发者 https://www.devze.com 2022-12-10 08:25 出处:网络
I am using the jQu开发者_StackOverflow中文版ery token input plugin and would like change its behavior when a token is added.

I am using the jQu开发者_StackOverflow中文版ery 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/"
    }
 });


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消