Custom Event For Custom JQuery Plugin - jquery-plugins

I made this jQuery plugin called removable when you click the objects button it slides up and should trigger a custom event like onDone.
Here's what I did (The codeing format is based on jQuery's http://docs.jquery.com/Plugins/Authoring):
init: function(){
return this.each(function(){
$('a', this).click(function(){
$(this).parent().slideUp(function(){
// Somehow trigger the onDone method
})
});
})
},
onDone: function(){
// Default action
},
and this is what I've done when calling the plugin
$('li').removable({
onDone: function(){
// Overwrite default action
},
})
How can this be done?

If all you need is to call it at the end of the animation, just pass it as the second argument to slideUp or even just call it with $(foo).MyPlugin.onDone() inside the callback function.
otherwise look at trigger and bind jQuery functions - you can use any string you want for those event types so you can trigger and bind a MyPluginDone event
EDIT: based on comments you want something simpler -
As it states in the article you quoted, the best way to provide override-able defaults to options is to have your plugin accept an options object, then to get the combined defaults+overrides you do:
var combinedOpts = $.extend({},defaults,overrides);
and get all the values to use from there...

Try this one.
(function($){
jQuery.fn.extend({
removable: function(options) {
var defaults = {
onDone: function(){alert('default action');}
};
var options = $.extend(defaults, options);
return this.each(function() {
$('a', this).click(function(){
$(this).parent().slideUp(function(){
options.onDone.call();
});
});
});
}
});
})(jQuery);
$('li').removable({
onDone: function(){
alert('Overwrite default action');
},
})

Related

Pass DataTable reference to the callback function on load

My current code is:
var CommissionLogs = $("#CommissionLogs").DataTable({
ajax: {
url: ajaxurl + '?action=pos&post_action=get_commissions'
},
'initComplete': function (settings, json){
//possible to access 'this'
this.api().columns(1);
}
});
I improved the code above as below with help :
var CommissionLogs = $("#CommissionLogs").DataTable({
ajax: {
url: ajaxurl + '?action=pos&post_action=get_commissions'
},
'initComplete': function(settings, json){
callbackFunction(settings);
}
});
function callbackFunction(settings){
var api = new $.fn.dataTable.Api( settings );
// api is accessible here.
}
Update :
Now I can access api from callback function. But I want use same callback with load() as below code.
CommissionLogs.ajax.url( newAjaxURL ).load( callbackFunction(), true);
But settings param is not accessible in load function.
I can clear and destroy datatable and re initialize always. But what will be the right way.
I think you need settings:
https://datatables.net/reference/type/DataTables.Settings
$('#example').dataTable( {
"initComplete": function(settings, json) {
myFunction(settings);
}
});
function myFunction(settings){
var api = new $.fn.dataTable.Api( settings );
// Output the data for the visible rows to the browser's console
// You might do something more useful with it!
console.log( api.rows( {page:'current'} ).data() );
}
Other option is re-use your var CommissionLogs variable throughout the code without using this, I recommend strongly this last option.
The dataTable.ajax.url().load() has not access to settings.
So can not call a callback function with settings.
But possible to use callback function without settings.
So here is an alternative way to use settings.
CommissionLogs.clear();// clear the table
CommissionLogs.destroy();// destroy the table
CommissionLogs = $("#CommissionLogs").DataTable({
ajax: {
url: newAjaxUrl
},
'initComplete': function (settings, json){
callbackDatatableFunciton(settings);
}
});

How to inherit from JQuery ajax?

I often use ajax request for that kind:
$.ajax({
done : function() {
alert( "success" );
},
fail : fonction() {
alert( "error" );
}
})
For one of my project I want to create some default action for each ajax request, and I wonder how can I implement it with JavaScript inheritance.
How I would like it looks like:
// Definition of the custom and global object in order to override some basic ajax options.
MyCustomAjaxObject = new $.ajax();
MyCustomAjaxObject.error( function () { /* some code for a default */});
// Further in the code, at the moment to trigger one of the ajax request
foo = new MyCustomAjaxObject({
url : myDestination,
data : someData
});
Do you know if it's possible to use inheritance of that kind with JavaScript?
$.ajax() as it isn't really designed to be used as a constructor, so inheritance probably won't accomplish what you want easily.
You can create a wrapper for it to modify the options or resulting $.Deferred as desired:
// A) default handler
function customAjax(options) {
if (!options.error) options.error = function () {
// ...
};
return $.ajax(options);
}
// B) always-in-queue handler
function customAjax(options) {
return $.ajax(options).error(function () {
// ...
});
}
And, if you just need to capture ajax events in general, jQuery does include global event bindings:
$(document).ajaxError(function () {
// ...
});

Marionette Layout: trigger event on child view

I have a layout view, with an itemView inside it. I have an event in my item view that triggers a save function. Inside that save function I would like to trigger another event that the layout captures.
So in the code below, in the onClickSave modelSaveSuccess I'd like to trigger a function in the parent layout, I have tried this.methodInParent() but it doesnt work
childView
define(["marionette", "underscore", "text!app/templates/client/form.html", "app/models/client"], function(Marionette, _, Template, Model) {
"use strict"
return Backbone.Marionette.ItemView.extend({
events: {
"submit #saveClient": "onClickSave"
},
onClickSave: function(ev) {
ev.preventDefault()
return this.model.save({}, {
success: function() {
console.log('success - trigger ')
},
error: function(request, error) {
console.log(error.responseText)
}
})
}
})
})
A good way to do it without introducing heavy coupling is to use Marionette's event aggregator as in the linked exemple if you use Backbone.Marionette.application.
// in your view
...
success: function() {
app.vent.trigger('myview:modelsaved');
}
...
// in your layout initialize()
...
app.vent.on('myview:modelsaved', function(){
console.log('model saved in itemView');
});
...
If you don't use Backbone.Marionette.Application you can always create your own Backbone.Wreqr.EventAggregator.

Attach the events ajaxStart() and ajaxStop() only to the current backbone view

I'm using backbone for an app that I'm building. In this app, I have a master view which render a template with 2 other views inside. One header view and another one with some content. The header view is just used to interact with the content view and has specific functions too.
In the header template and content template I have the same piece of code, an hidden DIV with a loader image that is displayed when an ajax call is made. The problem I have is that when I load the app for the first time (or when I refresh the content view), the content view is loading some data from an ajax request, but the loader is showing up in both the header and the content template (like if the ajaxStart() was a global event not attached to the view.
Here is the content view setup:
App.View.Content = Backbone.View.extend({
type:'test',
template: twig({
href: '/js/app/Template/Content.html.twig',
async: false
}),
block:{
test:twig({
href: '/js/app/Template/block/test.html.twig',
async: false
})
},
list:[],
showLoader: function(el){
console.log('loader: ', $('#ajax_loader', el));
$('#ajax_loader', el).show();
console.log('Ajax request started...');
},
hideLoader: function(el){
$('#ajax_loader', el).hide();
console.log('Ajax request ended...');
},
initialize: function(params)
{
this.el = params.el;
this.type = params.type || this.type;
var self = this;
this.el
.ajaxStart(function(){self.showLoader(self.el);})
.ajaxStop(function(){self.hideLoader(self.el);});
this.render(function(){
self.list = new App.Collection.ListCollection();
self.refresh(1, 10);
});
},
refresh:function(page, limit)
{
var self = this;
console.log('Refreshing...');
$('#id-list-content').fadeOut('fast', function(){
$(this).html('');
});
this.list.type = this.type;
this.list.page = page || 1;
this.list.limit = limit || 10;
this.list.fetch({
success: function(data){
//console.log(data.toJSON());
$.each(data.toJSON(), function(){
//console.log(this.type);
var tpl_block = self.block[this.type];
if (tpl_block != undefined) {
var block = tpl_block.render({
test: this
});
$(block).appendTo('#id-list-content');
}
});
$('#id-list-content').fadeIn('fast');
}
});
},
render: function(callback)
{
console.log('Rendering list...');
this.el.html(this.template.render({
}));
if (undefined != callback) {
callback();
}
}
});
As you can see I'm using an ugly piece of code to attach the ajaxStart / ajaxStop event:
this.el
.ajaxStart(function(){self.showLoader(self.el);})
.ajaxStop(function(){self.hideLoader(self.el);});
I use to have it like this:
this.el
.ajaxStart(self.showLoader())
.ajaxStop(self.hideLoader());
But for whatever reason that still undefined on my end, this.el was not defined in the showLoader() and hideLoader().
I was thinking that ajaxStart() and ajaxStop() was attached to the this.el DOM, and that only this view would be able to listen to it. But my headerView which has exactly the same setup (except for the twig template loaded) apparently receive the event and show the loader.
To be sure of this behavior, I've commented out the showLoader() in the content view, and the loader still show up in the header view.
I don't know what I'm doing wrong :(
EDIT (after answer from "mu is too short"):
my content view does now looks like this:
showLoader: function(){
//this.$('#ajax_loader').show();
console.log('Ajax request started...');
},
hideLoader: function(){
this.$('#ajax_loader').hide();
console.log('Ajax request ended...');
},
initialize: function(params)
{
var self = this;
console.log(this.el);
_.bindAll(this, 'showLoader', 'hideLoader');
this.$el
.ajaxStart(this.showLoader)
.ajaxStop(this.hideLoader);
this.render(function(){
self.list = new App.Collection.List();
self.refresh(1, 10);
});
},
...
render: function(callback)
{
console.log('Rendering post by page...');
this.$el.html(this.template.render({
}));
if (undefined != callback) {
callback();
}
}
and my header view:
...
showLoader: function(){
this.$('#ajax_loader').show();
//console.log('Ajax request started...');
},
hideLoader: function(el){
this.$('#ajax_loader').hide();
console.log('Ajax request ended...');
},
initialize: function(params)
{
var self = this;
_.bindAll(this, 'showLoader', 'hideLoader');
this.$el
.ajaxStart(this.showLoader)
.ajaxStop(this.hideLoader);
this.models.Link = new App.Model.Link();
this.render();
},
render: function(callback)
{
this.$el.html(this.template.render({
data: []
}));
if (undefined != callback) {
callback();
}
}
...
But the loader still showing up in the header view template
PS: this.showLoader() was not a typo as I wanted to call the function within the current backbone view.
The context (AKA this) for a JavaScript function depends on how the function is called, not on the context in which the function is defined. Given something like this:
var f = o.m;
f();
When you call o.m through the plain function f, this inside o.m will usually be the global context (window in a browser). You can also use apply and call to choose a different this so this:
f.call(o);
would make this the o that you'd expect it to be. I should mention that you can force your choice of this using bind in most JavaScript environments but I don't want to get too sidetracked.
The point is that this:
this.el
.ajaxStart(this.showLoader)
.ajaxStop(this.hideLoader);
isn't enough to ensure that showLoader and hideLoader will run in the right context; I'm also assuming that the parentheses you had at the end of showLoader and hideLoader were just typos.
The most common way to force a context in a Backbone application is to use _.bindAll in your initialize:
initialize: function(params) {
_.bindAll(this, 'showLoader', 'hideLoader');
//...
That essentially replaces this.showLoader and this.hideLoader with something that's, more or less, equivalent to your wrappers:
function() { self.showLoader(self.el) }
Once you have that _.bindAll in place, this:
this.el
.ajaxStart(this.showLoader)
.ajaxStop(this.hideLoader);
will work fine.
BTW, you don't need to do this:
this.el = params.el;
in your initialize, Backbone does that for you:
constructor / initialize new View([options])
[...] There are several special options that, if passed, will be attached directly to the view: model, collection, el, id, className, tagName and attributes.
And you don't need to do things like this:
$('#ajax_loader', el).show();
either, Backbone gives you a $ method in your view that does the same thing without hiding the el at the end of the argument list; doing it like this:
this.$('#ajax_loader').show();
is more idiomatic in Backbone.
Furthermore, this.el won't necessarily be a jQuery object so don't do this:
this.el.html(this.template.render({ ... }));
in your render, use the cached this.$el instead:
this.$el.html(this.template.render({ ... }));

dilemna with jqgrid and ajaxfileupload

I am using jqgrid and ajaxFileUpload.js script in order to pass parameters and files to a php script. The structure of the code is like this:
...
url:url_1.php,
beforeSubmit: function (postdata,formid)
{
$.ajaxFileUpload (
{
url: url_2.php,
...
success:
error:
}),
return[true,""];
},
afterSubmit: function(reponse,postdata)
{
...
return [true,'',''];
}
I have a dilemna:
According to the jqgrid behaviour, url_2.php is called, then url_1.php.
url_2.php handles the data (parameters + file), url_1.php handles nothing.
url_2.php could return an error or message (e.g "already exist") but, the errors are displayed in the form by the aftersubmit event, and this event receives error from url_1.php !!!
I suppose that I am obliged to put the ajaxfileupload in the beforesubmit event !!!
Any ideas to solve this dilemna ?
You can use jquery form plugin and jqGrid dataProxy method instead.
useDataProxy: true,
dataProxy : function (opts, act) {
opts.iframe = true;
var $form = $('#FrmGrid_' + $grid.jqGrid('getGridParam', 'id'));
//Prevent non-file inputs double serialization
var ele = $form.find('INPUT,TEXTAREA,SELECT').not(':file');
ele.each(function () {
$(this).data('name', $(this).attr('name'));
$(this).removeAttr('name');
});
//Send only previously generated data + files
$form.ajaxSubmit(opts);
//Set names back after form being submitted
setTimeout(function () {
ele.each(function () {
$(this).attr('name', $(this).data('name'));
});
}, 200);
};
For example http://jqgrid-php.net file fileUpload class uses this. This is described in How to force dataProxy call in form editing if editurl is set in jqgrid also.

Resources