繁体   English   中英

jQuery:UI小部件定义

[英]jQuery: UI widget definition

我有一个这样定义的小部件:

$.widget("ui.mywidget", {
    _init: function() {
        this.element.bind("keyup", function(event) {
            alert(this.options);
            alert(this.options.timeout);
        });
    }
});

并尝试这样称呼它:

$("input.mywidget").mywidget({timeout: 5});

我还使用this.element.keyup(function(event) { ... })样式重新定义了bind方法:没有区别。

但是,在keyup绑定中, this.options (并将其作为options引用) this.options定义。 我以为UI小部件框架允许这种类型的抽象。 难道我做错了什么?

bind()内部时, this将更改为引用引发事件的对象。 尝试:

$.widget("ui.mywidget", {
    _init: function(options) {
        var opts = this.options;
        this.element.bind("keyup", function(event) {
            alert(opts);
            alert(opts.timeout);
        });
    }
});

@戴夫说的是对的。 您也可以将“ this”设置为变量,而不是使用选项作为init函数的参数。 这是我经常看到的实施方式:

$.widget("ui.mywidget", {
    options: {
        timeout: 100
    },
    _init: function() {
        var self = this;
        self.element.bind("keyup", function(event) {
            alert(self.options);
            alert(self.options.timeout);
        });
    }
});

为什么停在那里? $ .proxy并编写更好的代码

$.widget("ui.mywidget", {
    _create: function() {

        //Under this syntax, _omgAlertsRule must be a method of 'this'
        this.element.bind("keyup", $.proxy( this, '_omgAlertsRule' ) );
    },
    _omgAlertsRule: function( event ){

        alert(this.options);
        alert(this.options.timeout);
    }
});

暂无
暂无

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

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