开发者

Passing a function in Jquery / Javascript

开发者 https://www.devze.com 2023-01-16 20:42 出处:网络
Good afternoon people\'s I have built a jquery plugin that I use on my site. The plugin is for suggestive input boxes and works fine.

Good afternoon people's

I have built a jquery plugin that I use on my site. The plugin is for suggestive input boxes and works fine.

One thing I need to add to it is the ability to pass a function in it's config to apply to the response of the ajax call that is made for the suggestive. I can't find anything on trusty old google about how to pass functions and have them applied in the scope of the plugin..

I need this because some responses update one field and some update 2 or more fields with different text held in the reponse and I dont want to keep duplicating the plugin allowing for this to happen. I am assuming that the javascript method "apply" is what I need to look at but I am totally confused

Does this even make sense on what I am trying to do ?开发者_开发百科 and if so can anyone help or point me in the right direction.

Thanks in advance

Alex


You are looking for .call() or .apply(). You can pass the context (i.e. scope) as the first parameter to both. .call() works like this:

yourCallback.call(this, param1, param2);

While .apply() works like this:

yourCallback.apply(this, [param1, param2]);

.apply() is very helpful when generating the parameters dynamically.


I would recommend you take advantage of the wonderful work being done by the jQuery UI team. The API is very well thought out and should give you everything you need.

http://docs.jquery.com/UI/Autocomplete


Javascript has closures. If you define a function like this:

{
   var a;

   function myFn() {
      b = a; // a is set
   }

   $('.c').autocomplete({callback: myFn});
   ...

This is usually sufficient to handle this case. In your set up code, include references to whatever you need as local variables, and they will exist even though the function itself goes out of context. This is a little weird to people not used to it, but powerful and useful.

Some plugins provide "context" variables you can set, and will be returned to you explicitly in your callback. Check the docs to see if those exist.

Finally, you can use apply to change the this that your function is called with. Functions in Javascript are (in general) standalone entities, and a single function can be called with this set to any sort of value. In the callback case, sometimes it's necessary to wrap a given callback and calls it in the right context. This looks like myFn.apply(newThis, params). You're actually caling the apply function on the function object, and providing it its context and parameters.

Hope this helps.

0

精彩评论

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