开发者

refactor jquery code

开发者 https://www.devze.com 2023-02-07 06:13 出处:网络
How can I remove the code at the end data(\"autocomplete\")... and put it in a function? var input = $(\"#CountryL\");

How can I remove the code at the end data("autocomplete")... and put it in a function?

    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;
    }; 

I'd like to be able to do:

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);


You were almost there. Simply extend 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);
      };
    });
  }
});

Usage is (nearly) exactly as you propose.

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

A bit of an explanation:

// 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
    });
  }
});
0

精彩评论

暂无评论...
验证码 换一张
取 消