简体   繁体   中英

jquery control chaining this loses scope

i was wondering if someone new how to keep a control with chaining in scope of the "this" key word. It breaks out of the chain when using .find(this).click does anyone know how to keep the chain from breaking

(function($) {
    $.fn.mycontrol = function() {
        $(window).resize(function() {
            alert('resize')
        }).scroll(function() {
            alert('scroll')    
        }).find(document).bind('init', function() {
            alert('scroll')
        }).ready(function() {
            $(this).trigger('init');
        }).find(this).click(function() {
            alert('click'); // $(this) loses scope here 
        });
})(jQuery);


$(document).ready(function() {
    $('#mycontrol').mycontrol()
});

If I understand correctly what you're looking for, you should be able to just save the value of this before you start your chaining:

(function($) {
    $.fn.mycontrol = function() {
        var that = this;
        $(window).resize(function() {
            alert('resize')
        }).scroll(function() {
            alert('scroll')    
        }).find(document).bind('init', function() {
            alert('scroll')
        }).ready(function() {
            $(that).trigger('init');
        }).find(that).click(function() {
            alert('click'); // $(this) loses scope here 
        });
})(jQuery);

Chaining creates unmaintainable code. Break it up into separate lines:

var $window =  $(window);

$window.resize(function() 
{
    alert('resize')
});

$window.scroll(function() 
{
   alert('scroll')    
});

// etc.

Then you can read it, you can step though it with the debugger, you can delete and remove logic with out breaking anything.

window is an object Window. This is window.document which contains HTML objects.

So $(window).find(this) return jquery empty object as $(window).find(document) too.

$(document).find(this) works instead which is equivalent of $(window.document) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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