2011-01-30 90 views
1

如何刪除末尾data("autocomplete")...的代碼並將其放入函數中?重構jQuery代碼

var input = $("#CountryL"); 

    $(input).autocomplete({ 
     minLength: 0, 
     source: $(input).data('url') 
    }).data("autocomplete")._renderItem = function (ul, item) { 
     var tmp = $("<div>").setTemplate($("#"+$(input).data('template')).html()); 
     tmp.processTemplate(item); 
     $("<li></li>").data("item.autocomplete", item) 
         .append($(tmp).html()) 
         .appendTo(ul); 
     return; 
    }; 

我希望能夠做到:

function templateOverride(object){ 

object.data("autocomplete")._renderItem = function (ul, item) { 
     var tmp = $("<div>").setTemplate($("#"+$(input).data('template')).html()); 
     tmp.processTemplate(item); 
     $("<li></li>").data("item.autocomplete", item) 
         .append($(tmp).html()) 
         .appendTo(ul); 
     return; 
} 


var input = $("#CountryL"); 

$(input).autocomplete({ 
     minLength: 0, 
     source: $(input).data('url') 
}).templateOverride(this); 

回答

2

你是幾乎沒有。簡單地擴展jQuery的:

$.fn.extend({ 
    templateOverride: function() { 
    return this.each(function() { 
     $(this).data("autocomplete")._renderItem = function (ul, item) { 
     var tmp = $("<div>").setTemplate($("#"+$(input).data('template')).html()); 
     tmp.processTemplate(item); 
     $("<li></li>").data("item.autocomplete", item) 
         .append($(tmp).html()) 
         .appendTo(ul); 
     }; 
    }); 
    } 
}); 

用法是(幾乎)完全按照自己的建議。

$("#CountryL").autocomplete({ 
    minLength: 0, 
    source: $(input).data('url') 
}).templateOverride(); 

的解釋的位:

// fn.extend() adds functions to the jQuery function library 
$.fn.extend({ 
    // it expects an object, so here we use object literal syntax (key: value) 
    templateOverride: function() { 
    // here "this" refers to the jQuery object you called the function on, 
    // which is an array, so we iterate it with each() *and* return it 
    // so jQuery function chaining does not break. 
    return this.each(function() { 
     // here "this" refers to the individual HTML objects, so we must wrap 
     // it in a jQuery call ($) to have access to its data() 
     $(this).data("autocomplete") // ... your code 
    }); 
    } 
});