使用jQuery UI Widget Factory创建实例变量的正确方法 [英] Proper way to create an instance variable using jQuery UI Widget Factory

查看:100
本文介绍了使用jQuery UI Widget Factory创建实例变量的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery UI小部件工厂。

I'm using the jQuery UI widget factory.

$.widget("myPlugin" , {

    options: {
    },

    _create: function() {
    },

    instanceVar: "huzzah!"

});

在测试中,看起来instanceVar实际上是原型的一部分。所以插件的所有实例都是一样的。

On testing, it looks as though instanceVar is actually part of the prototype. So it is the same across all instances of the plugin.

我可以通过将instanceVar放入选项来解决这个问题,如下所示:

I can fix this by putting instanceVar into options, like so:

$.widget("myPlugin" , {

    options: {
        instanceVar: "huzzah!"
    },

    _create: function() {
    },

});

然而这似乎很奇怪,因为instanceVar只是插件使用的内部变量 - 不是插件的用户应该能够改变。

However that seems odd, as instanceVar is just an internal variable for use by the plugin -- not something the user of the plugin should be able to change.

还有另一种(更好的)方法来实现这个目标吗?

Is there another (better) way to achieve this?

感谢您的帮助!

推荐答案

您可以在实例本身上存储私人数据,例如,在<$ c内$ c> _create ,你应该可以 this.instanceVar =huzzah!

You can store private data on the instance itself, for example, inside the _create, you should be able to do this.instanceVar = "huzzah!"

$.widget("ui.myPlugin", {

    options: {
        foo: "foo"
    },

    _create: function() {
        this.instanceVar = "huzzah!"
    },

    _setOption: function() {
        this.instanceVar = "worky!";
    },

    destroy: function() {
        console.log(this.instanceVar);  
    }

});

$(document).myPlugin().myPlugin("option","foo","bar").myPlugin("destroy"); // "worky"

$("body").myPlugin().myPlugin("destroy"); // "huzzah!

演示:http://jsfiddle.net/PGUqr/

这篇关于使用jQuery UI Widget Factory创建实例变量的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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