The following script allows jQueryUI's autocomplete to work with xeditable, and works as desired:
$(function(){
dialog.find('a.car').xEdit('autocomplete',{name:'carName', title:'Car Name', url: '/1.0/cars/', pk: carId, autocomplete: {
url: "/1.0/cars/",
params: {term:null, fields:['id','name']}
}});
});
$.fn.xEdit = function(type, options) {
var common={
placement: 'right',
ajaxOptions: {type: "PUT"},
send: 'always'
// pk: null, title: null, params: {name: null}, url: null, //Must be passed
}
// Not shown, but different actions will be performed based on "type"
options.params={name: options.name};
delete(options.name);
options.type='text';
//autocomplete is not used by xeditable but by jQueryUI autocomplete, but doesn't seem to hurt anything
this.editable($.extend({}, common, {value: null}, options))
.on('shown', function(e, editable) {
//console.log('on.show','this',this,'e',e,'editable',editable)
var elem=this;
var $input=editable.input.$input.val('');
var $button=$input.parent().next().find('button.editable-submit').css('opacity', 0.3)
.bind('click.prevent', function() {return false;});
var autocomplete={
source: function( request, response ) {
options.autocomplete.params.term=request.term;
$.getJSON( options.autocomplete.url, options.autocomplete.params, function(json) {
var data=[];
for (var j = 0; j < json.length; j++) {
data.push({id:json[j].id,label:json[j].name});
}
response(data);
} );
},
minLength: 2,
position: { my : "left top+20", at: "left bottom" },
select: function(e, ui) {
$input.blur();
$button.css('opacity', 1).unbind('click.prevent');
editable.option('params', {
value: ui.item.id,
name: options.params.name
});
}
};
if (typeof options.autocomplete.select != "undefined") autocomplete.select=options.autocomplete.select;
$input.focus(function() {
$button.css('opacity', 0.3).bind('click.prevent', function() {return false;});
})
.autocomplete(autocomplete)
.autocomplete('widget').click(function() {return false;});
});
break;
};
I now wish to be able to override the select: function(e, ui) {...}
(and maybe later the other methods) in xedit with a new function defined in options
, and try the following:
$(function(){
dialog.find('a.car').xEdit('autocomplete',{name:'carName', title:'Car Name', url: '/1.0/cars/', pk: carId, autocomplete: {
url: "/1.0/cars/",
params: {term:null, fields:['id','name']},
select: function(e, ui) {
//Be able to do something different
$input.blur();
$button.css('opacity', 1).unbind('click.prevent');
editable.option('params', {
value: ui.item.id,
name: options.params.name,
model: 123
}
);
}
}});
});
But it results in errors stating that e
, ui
, $input
, $button
, editable
, options
are all undefined. I think it is due to defining the new function in a different variable scope.
How can I define an object in one variable scope, and then apply another scope to it?
PS. I expect how I am doing this is pretty ugly, and if there is a prettier way, feel free to comment.