2011-01-30 4 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 
    }); 
    } 
});