Proper way to create an instance variable using jQuery UI Widget Factory

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-10 12:43:33

问题


I'm using the jQuery UI widget factory.

$.widget("myPlugin" , {

    options: {
    },

    _create: function() {
    },

    instanceVar: "huzzah!"

});

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

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

$.widget("myPlugin" , {

    options: {
        instanceVar: "huzzah!"
    },

    _create: function() {
    },

});

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?

Thanks for your help!


回答1:


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!

Demo: http://jsfiddle.net/PGUqr/



来源:https://stackoverflow.com/questions/13867704/proper-way-to-create-an-instance-variable-using-jquery-ui-widget-factory

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!