简体   繁体   English

jQuery插件开发执行功能设置

[英]jQuery plugin development execute a setting that is a function

I'm fiddling around trying to put together an autocomplete jQuery plugin. 我在摆弄一个自动完成的jQuery插件。 I know there's a default one, but I found that I sometimes just need something really simple and also would like to adjust behavior to my needs. 我知道有一个默认值,但是我发现有时我只需要一些非常简单的东西,并且还想根据自己的需要调整行为。 Last it's kinda fun to expierence around. 最后,体验一下还挺有趣的。 If it turns out into something useful I might put together a small plugin site for it. 如果结果有用,我可能会为它建立一个小型插件站点。

Anyway; 无论如何; the plugin has some options. 该插件有一些选项。 One of them is dataSource . 其中之一是dataSource It can be an object, string or function. 它可以是对象,字符串或函数。 I'm trying to accomplish the task to get the function executed. 我正在尝试完成任务以使功能得以执行。 I've tried to eval it, but when I console.log it just logs the javascript code the function consists of. 我试图进行eval ,但是当我console.log时,它只记录该函数所包含的javascript代码。

Implementation of the plugin 插件的实现

$('#search3').myAutoCompletePlugin({
    completeOnEnter: false,
    delay: 200,
    dataSource: function() {
        console.log('Hello!');
    }
});

In the plugin's code, this is how I try to execute it. 在插件的代码中,这就是我尝试执行它的方式。

...
getResults: function() {
    var self = this,
        dataSourceType = typeof self.options.dataSource;

    self.request.items = [];

    ...
    } else if (dataSourceType == 'function') {
        // Callback as source, execute it
        self.request.items = eval(self.options.dataSource);
        console.log('function executed');
        console.log(self.request.items);
    } 
    ...
},
...

I would expect it log "Hello!", but what I get is: 我希望它记录为“ Hello!”,但是我得到的是:

function executed
function () {
        console.log('Hello!');
    }

If the dataSource property is a function you can then just call it directly, there's no need for eval() : 如果dataSource属性是一个函数,则可以直接调用它,不需要eval()

else if (typeof self.options.dataSource == 'function') {
    self.request.items = self.options.dataSource();
    console.log('function executed');
    console.log(self.request.items);
} 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM