init函数如何在插件中工作? [英] How does the init function work in plugins?

查看:91
本文介绍了init函数如何在插件中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这是一个基本问题,但我对JQuery插件的工作方式和Google的帮助不甚了解.

Sorry if this is a base question but I seem to have a misconception on how plugins in JQuery work and Google ain't helping much.

想象我有:

methods = {
    init : function(opts){

        options = $.extend(options, opts);

        return this.each(function(){
            data = $(this).data('prodigal');

            if(!data){

                if(options.isActive === false){
                    $(options.tpl.overlay).css({ 'opacity': options.overlay.opacity }).appendTo('body');
                    options.isActive = true;
                }
            }
        });
    }
};

现在options.isActivetruefalse的布尔值,表示是否应将options.tpl.overlay选项添加到文档的body中.这样可以确保我的options.tpl.overlay仅附加一次到文档,并且可以正常工作,但是我不确定它如何工作.

Now options.isActive is a boolean of true or false to say whether or not the options.tpl.overlay option should be added to the body of the document. It ensures my options.tpl.overlay appends only once to the document and it works, but I am unsure how it works.

当我打电话时:

$('.view_title_images').prodigal();
$('.glglg').prodigal();

它仍然只添加一次.我总是被认为是插件已形成,并且您每次执行调用"都会调用init函数,即$('.view_title_images,.glglg').prodigal();会形成并调用init函数一次.

It still only adds once. I was always led to believe that the plugin is formed and the init function called for every "call" you make, i.e. $('.view_title_images,.glglg').prodigal(); would form and call the init function once.

那么init函数在JQuery插件中的运行情况如何?

So how exactly does the init function run in a JQuery plugin?

推荐答案

我看到了这种现象,因为该插件实际上是在首次作为静态对象在jQuery插件框架中运行时实例化的.

I am seeing this behaviour because the plugin is actually instantiated the first time it is run as a static object within the jQuery plugin framework.

因此,每次对init函数的后续调用都将调用此全局对象.由于options对象是对静态对象中该对象的引用,因此每次实际保存布尔值时都会更改该布尔值,以供以后调用该插件.

So every successive call to the init function will call this global object. Since the options object is a reference to that object in the static object changing the boolean each time is actually saved for future calls to the plugin.

这篇关于init函数如何在插件中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆