jQuery function: pass callback functions as optional arguments to another function - javascript

I've written the following convenience function to let me easily put jquery UI autocomplete on elements.
jQuery.fn.bindAutocomplete = function() {
$(this).each( function() {
$(this).autocomplete({
source: $(this).data('autocomplete-source')
});
});
}
I always use the convention of attaching data-autocomplete-source to an element so I can call this anywhere just like so:
$('input#name').bindAutocomplete();
Now, the autocomplete function can take callback functions as optional arguments after the options hash. I almost never need to mess with that, but I've found that in a small number of instances I'd like to pass a success function through. Obviously I can just rewrite the full autocomplete function when I need to pass it callbacks, but I'd rather just rewrite my bindAutocomplete() function so it can accept optional callback functions and pass them through to autocomplete().
So, how do you do that?
Update
I tried this, based on a close but not quite answer below:
jQuery.fn.bindAutocomplete = function(callbacks) {
$(this).each( function(callbacks) {
options = $.extend({source: $(this).data('autocomplete-source')}, callbacks);
$(this).autocomplete(options);
});
}
This binds autocomplete correctly whether you pass callbacks in or not, but if you do pass callbacks they don't get called.
Ie: the following triggered autocomplete but not the callback.
$('input#name').bindAutocomplete({ select: function(){alert("working");} })

I guess you can do this if that's what you mean...
jQuery.fn.bindAutocomplete = function( opts ) {
return this.each(function(){
opts = $.extend({
source: $(this).data('autocomplete-source')
}, opts);
$(this).autocomplete( opts );
});
}
$('input#name').bindAutocomplete({
change: function() { ... },
close: function() { ... }
});

Related

Call second parameter without set first

I'm developing a jQuery plugin, and I want to know if there's any possibility to get the second parameter without set the first parameter.
MCVE:
https://jsfiddle.net/2fgb5agL/
//jQuery
$.fn.myPlugin = function(param1,param2) {
return this.each( function() {
if (param2) {
alert("param2 ok");
}
});
};
//Call the plugin
$("#call").click(function() {
$(this).myPlugin("", "xyz");
});
What I mean is: it's possible to call $(element).myPlugin("xyz") and expect the plugin recognize a defined string (ex. "xyz") and then 'do something' (call other function).
So, I don't gonna need to call $(element).myPlugin(undefined,"xyz") for get the second param without setting the first one.
Thanks for reading.
p.s.: What I want to achieve is a cleaner code.
Unless the parameter types are strictly different, you can't even create a distinction inside the function.
Is usual to use a single object parameter as argument like so:
//jQuery
$.fn.myPlugin = function(options) {
return this.each( function() {
if (options.param2) {
alert("param2 ok");
}
});
};
$("#call").click(function() {
$(this).myPlugin({ param1: "", param2: "xyz" });
});
This way you can chose which argument to pass for your plugin. For example: $(this).myPlugin({ param2: "xyz" });

How to detect when an .html() function is called in jQuery?

The problem is simple. I have a massive javascript application. And there are lot of times in the app where I use code which looks something like this -
$('#treat').html(new_data);
....
....
$('#cool').html(some_html_data);
....
....
$('#not_cool').html(ajax_data);
So what I want to do is, everytime this html() function is called I want to execute a set of functions.
function do_these_things_every_time_data_is_loaded_into_a_div()
{
$('select').customSelect();
$('input').changeStyle();
etc.
}
How do I do this? Thank you.
You can use the custom event handlers for that:
$('#treat').html(new_data);
// Trigger the custom event after html change
$('#treat').trigger('custom');
// Custom event handler
$('#treat').on('custom', function( event) {
// do_these_things_every_time_data_is_loaded_into_a_div
alert('Html had changed!');
});
UPDATE
Based on answer over here and with some modifications you can do this:
// create a reference to the old `.html()` function
$.fn.htmlOriginal = $.fn.html;
// redefine the `.html()` function to accept a callback
$.fn.html = function (html, callback) {
// run the old `.html()` function with the first parameter
this.htmlOriginal(html);
// run the callback (if it is defined)
if (typeof callback == "function") {
callback();
}
}
$("#treat").html(new_data, function () {
do_these_things_every_time_data_is_loaded_into_a_div();
});
$("#cool").html(new_data, function () {
do_these_things_every_time_data_is_loaded_into_a_div();
});
Easily maintainable and less code as per your requirements.
You can overwrite the jQuery.fn.html() method, as described in Override jQuery functions
For example, use this:
var oHtml = jQuery.fn.html;
jQuery.fn.html = function(value) {
if(typeof value !== "undefined")
{
jQuery('select').customSelect();
jQuery('input').changeStyle();
}
// Now go back to jQuery's original html()
return oHtml.apply(this, value);
};
When html() is called it usually make the DOM object changes, so you can look for DOM change event handler, it is called whenever your HTML of main page change. I found
Is there a JavaScript/jQuery DOM change listener?
if this help your cause.
You can replace the html function with your own function and then call the function html:
$.fn.html = (function(oldHtml) {
var _oldHtml = oldHtml;
return function(param) {
// your code
alert(param);
return _oldHtml.apply(this, [param]);
};
})($.fn.html);
I have a little script for you. Insert that into your javascript:
//#Author Karl-André Gagnon
$.hook = function(){
$.each(arguments, function(){
var fn = this
if(!$.fn['hooked'+fn]){
$.fn['hooked'+fn] = $.fn[fn];
$.fn[fn] = function(){
var r = $.fn['hooked'+fn].apply(this, arguments);
$(this).trigger(fn, arguments);
return r
}
}
})
}
This allow you to "hook" jQuery function and trigger an event when you call it.
Here how you use it, you first bind the function you want to trigger. In your case, it will be .html():
$.hook('html');
Then you add an event listener with .on. It there is no dynamicly added element, you can use direct binding, else, delegated evets work :
$(document).on('html', '#threat, #cool, #not_cool',function(){
alert('B');
})
The function will launch everytime #threat, #cool or #not_cool are calling .html.
The $.hook plugin is not fully texted, some bug may be here but for your HTML, it work.
Example : http://jsfiddle.net/5svVQ/

What's the easiest way i can pass an element as a first argument to event handlers in JavaScript?

I know that having the value of this being changed to the element receiving the event in event handling functions is pretty useful. However, I'd like to make my functions always be called in my application context, and not in an element context. This way, I can use them as event handlers and in other ways such as in setTimeout calls.
So, code like this:
window.app = (function () {
var that = {
millerTime: function () {},
changeEl: function (el) {
el = el || this;
// rest of code...
that.millerTime();
}
};
return that;
}());
could just be like this:
window.app = (function () {
return {
millerTime: function () {},
changeEl: function (el) {
// rest of code...
this.millerTime();
}
};
}());
The first way just looks confusing to me. Is there a good easy way to pass the element receiving the event as the first argument (preferably a jQuery-wrapped element) to my event handling function and call within the context of app? Let's say I bind a bunch of event handlers using jQuery. I don't want to have to include anonymous functions all the time:
$('body').on('click', function (event) {
app.changeEl.call(app, $(this), event); // would be nice to get event too
});
I need a single function that will take care of this all for me. At this point I feel like there's no getting around passing an anonymous function, but I just want to see if someone might have a solution.
My attempt at it:
function overrideContext (event, fn) {
if (!(this instanceof HTMLElement) ||
typeof event === 'undefined'
) {
return overrideContext;
}
// at this point we know jQuery called this function // ??
var el = $(this);
fn.call(app, el, event);
}
$('body').on('click', overrideContext(undefined, app.changeEl));
Using Function.prototype.bind (which I am new to), I still can't get the element:
window.app = (function () {
return {
millerTime: function () {},
changeEl: function (el) {
// rest of code...
console.log(this); // app
this.millerTime();
}
};
}());
function overrideContext (evt, fn) {
var el = $(this); // $(Window)
console.log(arguments); // [undefined, app.changeEl, p.Event]
fn.call(app, el, event);
}
$('body').on('click', overrideContext.bind(null, undefined, app.changeEl));
Using $('body').on('click', overrideContext.bind(app.changeEl)); instead, this points to my app.changeEl function and my arguments length is 1 and contains only p.Event. I still can't get the element in either instance.
Defining a function like this should give you what you want:
function wrap(func) {
// Return the function which is passed to `on()`, which does the hard work.
return function () {
// This gets called when the event is fired. Call the handler
// specified, with it's context set to `window.app`, and pass
// the jQuery element (`$(this)`) as it's first parameter.
func.call(window.app, $(this) /*, other parameters (e?)*/);
}
}
You'd then use it like so;
$('body').on('click', wrap(app.changeEl));
For more info, see Function.call()
Additionally, I'd like to recommend against this approach. Well versed JavaScript programmers expect the context to change in timeouts and event handlers. Taking this fundamental away from them is like me dropping you in the Sahara with no compass.

How to always call a function from a JavaScript object literal, not only when the object is created

I hope my title isn't too confusing. An example first. I have the following code that configures the read operation for a Kendo UI data source. I am trying to filter all reads based on the selected company id, but my getSelectedCompanyId function is only ever called once, when the page loads. The code below is too long to include all here, so just an excerpt.
$(function () {
function getSelectedCompanyId() {
var id = $("#CompanyId").val();
return id;
}
$("#CompanyId").kendoDropDownList({
change: function () {
grid.dataSource.read();
}
});
var departmentIndexDataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("ListForCompanyIdJson", "Department")' + '?companyId=' + getSelectedCompanyId(),
type: "GET"
},
The ListForCompanyIdJson action is always called with the value selected in the dropdown when $("#CompanyId").kendoDropDownList() is called. I want this function to be called whenever I call grid.dataSource.read().
I realize this might be highly specific to the Kendo stuff, but maybe it's something I can solve with plain JavaScript closures and some help.
You could install a replacement function for grid.dataSource.read() that always calls your function first and then calls grid.dataSource.read().
For example:
grid.dataSource.oldRead = grid.dataSource.read;
grid.dataSource.read = function() {
// call your function here
return grid.datasource.oldRead.apply(this, arguments);
}
Or, if you want to be able to call one sometimes and one other times, you can just make a new method that provides the new behavior and use it when you want to:
grid.dataSource.myread = function() {
// call your function here
return grid.datasource.read.apply(this, arguments);
}

Passing collection.fetch as a named function to collection.bind does not work

I have two Backbone collections. I want to bind to the reset event one one. When that event is fired, I want to call fetch on the second collection, like so:
App.collections.movies.bind("reset", App.collections.theaters.fetch);
The second fetch never fires though. However, if I pass an anonymous function that calls theaters.fetch, it works no problem:
App.collections.movies.bind("reset", function () { App.collections.theaters.fetch(); });
Any idea why this might be the case?
Heres my full code. I'm not showing any of the models or collections, because it's a lot of code, but let me know if you think that might be the source of the problem:
var App = {
init: function () {
App.collections.theaters = new App.Theaters();
App.collections.movies = new App.Movies();
App.events.bind();
App.events.fetch();
},
events: {
bind: function () {
App.collections.theaters.bind("reset", App.theaterManager.assign);
App.collections.movies.bind("reset", function () { App.collections.theaters.fetch(); });
},
fetch: function () {
App.collections.movies.fetch();
}
},
collections: {},
views: {},
theaterManager: {
// Provide each model that requires theaters with the right data
assign: function () {
// Get all theaters associated with each theater
App.theaterManager.addToCollection("theaters");
// Get all theaters associated with each movie
App.theaterManager.addToCollection("movies");
},
// Add theaters to a collection
addToCollection: function (collection) {
App.collections[collection].each(function (item) {
item.theaters = App.theaterManager.getTheaters(item.get(("theaters")));
});
},
// Returns a collection of Theaters models based on a list of ids
getTheaters: function () {
var args;
if (!arguments) {
return [];
}
if (_.isArray(arguments[0])) {
args = arguments[0];
} else {
args = Array.prototype.slice.call(arguments);
}
return new App.Theaters(_.map(args, function (id) {
return App.collections.theaters.get(id);
}));
}
}
};
$(function () {
App.init();
});
This all has to do with function context. It is a common confusion with the way functions are called in Javascript.
In your first way, you are handing a function to be called, but there is no context defined. This means that whoever calls it will become "this". It is likely that the equivalent will be of calling App.collections.movies.fetch() which is not what you want. At least, I am guessing that is what the context will be. It is difficult to know for sure... it might be jQuery, it might be Backbone.sync. The only way to tell is by putting a breakpoint in the Backbone.collections.fetch function and print out the this variable. Whatever the case, it won't be what you want it to be.
In the second case, you hand it a function again but internally, you specify the context in which the function is called. In this case, fetch gets called with App.collections.theaters as the context.
... was that clear?

Categories

Resources