1

I am using jQuery v1.8.3 and jQuery UI v1.9.2. I have implemented the Autocomplete widget this way:

$('#input_id').autocomplete({
  create: function (event, ui) {
    // Initialize data
    $(this).data( 'custom', { property1: 'Hello', property2: { num: 1, funct: function() { ... return value } } );

    alert($(this).data('custom').property1) // Display 'Hello'
  },

  select: function(event, ui) {
    alert($(this).data('custom').property1) // Display 'Hello'
  },

  source: function(request, response) {
    alert($(this).data('custom').property1) // Display 'undefined'
    alert(this.data('custom').property1)    // I get 'TypeError: this.data is not a function'
  }
});

Why in the source option I get undefined while in create and select events I get Hello? How should I properly access the number property in the search option context so to get Hello?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
user12882
  • 4,702
  • 9
  • 39
  • 54

1 Answers1

3

You're getting undefined there, because apparently this inside source function refers to anonymous function, not to the INPUT you're assigning data to in create function.

Use other means to access input inside source function.

$('#input_id').autocomplete({
    create: function (event, ui) {
        // when using "this" here, you're refering to #input_id input
    },
    source: function(request, response) {
        // when using "this" here, you're refering to anonymous function
    }
});

To access your data within source function use following:

 // ...
 source: function(request, response) {
     // you don't need to wrap this.element in jQuery again since it is already wrapped
     this.element.data('custom').property1
 }

Demo for future quick reference: http://jsbin.com/ojesig/1/edit

WTK
  • 16,583
  • 6
  • 35
  • 45
  • How can I refer to `#input_id` inside `source` "block"? – user12882 Dec 06 '12 at 13:03
  • @user12882 Use that: $(this.element).data('custom').property1 – A. Wolff Dec 06 '12 at 13:03
  • @roasted Thx for the tip - a quick note though - `this.element` is already wrapped in jQuery so no need to do it again to read its data. – WTK Dec 06 '12 at 13:07
  • I opened a [new related question](http://stackoverflow.com/questions/13749724/how-to-refactoring-a-self-declaration-depending-on-the-current-context) to make things better... – user12882 Dec 06 '12 at 18:04