簡體   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