replace fn by callback + add before and after

This commit is contained in:
a-Sansara 2015-12-25 00:34:11 +01:00
parent 6685c12bc1
commit dfc6a08200
4 changed files with 100 additions and 38 deletions

View File

@ -32,7 +32,8 @@
$bt.append('#test', "<b>it's cool to rewrite</b>", null, null, '1449974562012');
// rewrite content to specified browser tab with callback
$bt.html('#test', "<b>it's cool to rewrite</b>", null, function() { alert('callback'); }, '1449974562012');
// callback must be define before command with method $bt.setCallback('callbackname', callback);
$bt.html('#test', "<b>it's cool to rewrite</b>", null, 'callbackname', '1449974562012');
// append content to specified browser tab on specific frame
$bt.append('#test', "<b>it's cool to rewrite</b>", 'frameName', null, '1449974562012');
@ -41,7 +42,7 @@
$bt.sync('#test');
// perform a node synchro to specified browser tab on specific frame with callback
$bt.sync('#test', 'frameName', callback, '1449974562012');
$bt.sync('#test', 'frameName', 'callbackname', '1449974562012');
// reload other browser tabs
$bt.reload();
@ -73,6 +74,15 @@
}
}
// it's also possible to define a before and after function :
$bt.before = function(cmd) {
$bt.log("i'm fired before every command");
}
$bt.after = function(cmd) {
$bt.log("i'm fired after every command");
}
// send a custom command to other browser tabs
$bt.send({ name : $bt.CMD_CUSTOM, customKey : 'customValue' });

View File

@ -1,7 +1,7 @@
<!doctype>
<html>
<head>
<title>pluie.org bt demo - v0.6</title>
<title>pluie.org bt demo - v0.7</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style>
body { background-color:#888; color:white; font-family:arial; font-size:1.3rem; }
@ -17,14 +17,15 @@
</head>
<body>
<h2>pluie.org bt demo : </h2>
<span>author : a-sansara - version : 0.6</span>
<span>author : a-sansara - version : 0.7</span>
<div>
<p> Manage commnunication between browser tabs.</p>
<p> this js lib can perform several actions on browser tabs like :<br/>
<ul><li>append/rewrite/synchro node on all (other) tabs or a specific tab (and possibly on specific frame context) eventually with callback.</li>
<li>reload all tabs or a specific tab with specified url or tab 's current url</li>
<li>perform your custom actions on all tabs or specific tab</li>
<li>(*new) kill zombies tabs onload</li>
<li>kill zombies tabs onload</li>
<li>(*new) define custom before and after command functions</li>
</ul>
</p>
<h3>Static actions</h3>
@ -37,7 +38,9 @@ enter txt or html : <br/>
<textarea id="data"></textarea>
<br/>select your action<br/>
<button class="cmd-append">dom append</button>
<button class="cmd-append-cb">dom append with callback</button>
<button class="cmd-html">dom html</button>
<button class="cmd-html">dom html with before</button>
<button class="cmd-sync">dom sync</button>
<button class="cmd-tarsync">target dom sync</button>
<button class="cmd-reload">tab reload</button>
@ -64,7 +67,17 @@ $bt.on = function(cmd) {
}
//
$(document).ready(function() {
$bt.init();
$bt.init(function() {
$bt.setCallback('mycallback', function(cmd) {
alert("i'm the callback of cmd "+cmd.name);
});
$bt.before = function(cmd) {
console.log('before cmd '+cmd.name);
}
$bt.after = function(cmd) {
console.log('after cmd '+cmd.name);
}
});
var bind = function(call) {
var html = $('#data').val();
if (html.length > 0) call(html)
@ -75,6 +88,11 @@ $(document).ready(function() {
$bt.append('#test', data);
});
});
$('.cmd-append-cb').on('click', function(){
bind(function(data) {
$bt.append('#test', data, null, 'mycallback');
});
});
$('.cmd-html').on('click', function(){
bind(function(data) {
$bt.html('#test', data);

2
src/bt-min.js vendored
View File

@ -1 +1 @@
/* by a-sansara - v 0.6 - https://github.com/pluie-org/bt */var $l=function(){var a=localStorage;return{clear:function(){return a.clear()},get:function(n){return a.getItem(n)},rem:function(n){return a.removeItem(n)},set:function(n,o){return a.setItem(n,o)}}}(),$j=function(){var a=JSON;return{str:function(n){return a.stringify(n)},obj:function(s){return a.parse(s)}}}(),$bt={VERSION:.6,TRACE:!0&&!$.isNone(console),LS_TABS:"bt.list",LS_CURTAB:"bt.current",LS_CMD:"bt.event",CMD_SYNC:"bt.sync",CMD_VAR_SET:"bt.set",CMD_VAR_GET:"bt.get",CMD_APPEND:"bt.dom.append",CMD_HTML:"bt.dom.rewrite",CMD_RELOAD:"bt.reload",CMD_ZOMBKILL:"bt.zombkill",CMD_DONTKILL:"bt.dontkill",vars:[],zomblist:[],zkillonload:!0,zombTimeout:250,init:function(n){this._init(n)},on:function(n){this.log(n)},log:function(n){this.TRACE&&console.log(n)},send:function(n){n.uid=this.id+Math.random(),n.from=this.id,$.isNone(n.to)&&(n.to="*"),n=$j.str(n),$bt.log("sending cmd : "+this.LS_CMD+" : "+n),$l.set(this.LS_CMD,n),$l.rem(this.LS_CMD)},append:function(n,o,i,b,c){this._dom(this.CMD_APPEND,i,n,o,b,c)},html:function(n,o,i,b,c){this._dom(this.CMD_HTML,i,n,o,b,c)},sync:function(n,o,i,b){var c=$.isNone(o)||null==o?document:parent.frames[o].document;this._dom(this.CMD_HTML,o,n,$(n,c).html(),i,b)},reload:function(n,o){$bt.send({name:$bt.CMD_RELOAD,url:n,to:o?o:"*"})},zombkill:function(n,o){var i=(new Date).getTime();$bt.zomblist[""+i]=[],$bt.list.forEach(function(n){n!=$bt.id&&($bt.zomblist[""+i]["ping"+n]="")}),$bt.send({name:$bt.CMD_ZOMBKILL,askid:i,to:"*"});var b=setTimeout(function(){$bt._refresh();for(var o in $bt.zomblist[""+i])if("pong"!=$bt.zomblist[""+i][o]){var c=$bt.list.indexOf(parseInt(o.substring(4)));c>-1&&$bt.list.splice(c,1)}$l.set($bt.LS_TABS,$j.str($bt.list)),$bt._broadcast(),$bt.log($bt.list),clearTimeout(b),$.isFunc(n)&&n()},o?o:$bt.zombTimeout)},_dontkill:function(n,o){$bt.send({name:$bt.CMD_DONTKILL,askid:n,to:o})},_refresh:function(){$bt.list=$j.obj($l.get($bt.LS_TABS))},_broadcast:function(){$bt.send({name:$bt.CMD_SYNC})},_remove:function(n){n||(n=$bt.id);var o=$bt.list.indexOf(n);o>-1&&$bt.list.splice(o,1)},_init:function(n){$(window).on("beforeunload",$bt._unload),$(window).on("storage",$bt._cmd),$(window).on("focus",$bt._focus),$bt.id=(new Date).getTime();var t=$l.get($bt.LS_TABS);$bt.list=null==t?[]:$j.obj(t),$bt.list.push($bt.id),$l.set($bt.LS_TABS,$j.str($bt.list)),$bt._broadcast(),$bt.log($bt.list),$bt.zkillonload?$bt.zombkill(n):$.isFunc(n)&&n()},_dom:function(n,o,s,i,b,c){$bt.send({name:n,context:o,selector:s,data:i,fn:b,to:c?c:"*"})},_unload:function(){return $bt._refresh(),$bt._remove(),$l.set($bt.LS_TABS,$j.str($bt.list)),$bt._broadcast(),null},_focus:function(){$l.set($bt.LS_CURTAB,$bt.id)},_cmd:function(e){if($.isNone(e.originalEvent)||(e=e.originalEvent),e.key==$bt.LS_CMD){var cmd=$j.obj(e.newValue);if(cmd)if($bt.log("RECEIVING cmd "+cmd.name+" : "),"*"==cmd.to||cmd.to==$bt.id){$bt.log("do "+cmd.name),$bt.log(cmd);try{$.isNone(cmd.context)||($bt.log(cmd.context),cmd.context=window.parent.frames[cmd.context].document,$bt.log(cmd.context))}catch(e){$bt.log("bad context "+cmd.context+" : "+e.message)}switch(cmd.name){case $bt.CMD_SYNC:$bt._refresh(),$bt.log($bt.list);break;case $bt.CMD_APPEND:$(cmd.selector,cmd.context).append(cmd.data);break;case $bt.CMD_HTML:$(cmd.selector,cmd.context).html(cmd.data);break;case $bt.CMD_RELOAD:window.location=$.isNone(cmd.url)?window.location:cmd.url;break;case $bt.CMD_ZOMBKILL:$bt._dontkill(cmd.askid,cmd.from);break;case $bt.CMD_DONTKILL:$bt.zomblist[""+cmd.askid]["ping"+cmd.from]="pong";break;default:$.isFunc($bt.on)&&$bt.on(cmd)}if($.isStr(cmd.fn)&&cmd.fn.length>0){$bt.log(cmd.fn);var f=eval("window."+cmd.fn);$.isFunc(f)&&f()}}else $bt.log("ignoring (not target)")}}};
/* by a-sansara - v 0.7 - https://github.com/pluie-org/bt */var $l=function(){var a=localStorage;return{clear:function(){return a.clear()},get:function(n){return a.getItem(n)},rem:function(n){return a.removeItem(n)},set:function(n,o){return a.setItem(n,o)}}}(),$j=function(){var a=JSON;return{str:function(n){return a.stringify(n)},obj:function(s){return a.parse(s)}}}(),$bt={VERSION:.7,TRACE:!0&&!$.isNone(console),LS_TABS:"bt.list",LS_CURTAB:"bt.current",LS_CMD:"bt.event",CMD_SYNC:"bt.sync",CMD_VAR_SET:"bt.set",CMD_VAR_GET:"bt.get",CMD_APPEND:"bt.dom.append",CMD_HTML:"bt.dom.rewrite",CMD_RELOAD:"bt.reload",CMD_ZOMBKILL:"bt.zombkill",CMD_DONTKILL:"bt.dontkill",vars:[],callbacks:[],zomblist:[],zkillonload:!0,zombTimeout:250,init:function(n){this._init(n)},log:function(n){this.TRACE&&console.log(n)},send:function(n){n.uid=this.id+Math.random(),n.from=this.id,$.isNone(n.to)&&(n.to="*"),n=$j.str(n),$bt.log("sending cmd : "+this.LS_CMD+" : "+n),$l.set(this.LS_CMD,n),$l.rem(this.LS_CMD)},append:function(n,o,i,b,l){this._dom(this.CMD_APPEND,i,n,o,b,l)},html:function(n,o,i,b,l){this._dom(this.CMD_HTML,i,n,o,b,l)},sync:function(n,o,i,b){var l=$.isNone(o)||null==o?document:parent.frames[o].document;this._dom(this.CMD_HTML,o,n,$(n,l).html(),i,b)},reload:function(n,o){$bt.send({name:$bt.CMD_RELOAD,url:n,to:o?o:"*"})},setCallback:function(n,o){$.isNone($bt.callbacks[n])?$bt.callbacks[n]=o:console.log("BT ERROR : callback name already exist")},zombkill:function(n,o){var i=(new Date).getTime();$bt.zomblist[""+i]=[],$bt.list.forEach(function(n){n!=$bt.id&&($bt.zomblist[""+i]["ping"+n]="")}),$bt.send({name:$bt.CMD_ZOMBKILL,askid:i,to:"*"});var b=setTimeout(function(){$bt._refresh();for(var o in $bt.zomblist[""+i])if("pong"!=$bt.zomblist[""+i][o]){var l=$bt.list.indexOf(parseInt(o.substring(4)));l>-1&&$bt.list.splice(l,1)}$l.set($bt.LS_TABS,$j.str($bt.list)),$bt._broadcast(),$bt.log($bt.list),clearTimeout(b),$.isFunc(n)&&n()},o?o:$bt.zombTimeout)},_dontkill:function(n,o){$bt.send({name:$bt.CMD_DONTKILL,askid:n,to:o})},_refresh:function(){$bt.list=$j.obj($l.get($bt.LS_TABS))},_broadcast:function(){$bt.send({name:$bt.CMD_SYNC})},_remove:function(n){n||(n=$bt.id);var o=$bt.list.indexOf(n);o>-1&&$bt.list.splice(o,1)},_init:function(n){$(window).on("beforeunload",$bt._unload),$(window).on("storage",$bt._cmd),$(window).on("focus",$bt._focus),$bt.id=(new Date).getTime();var t=$l.get($bt.LS_TABS);$bt.list=null==t?[]:$j.obj(t),$bt.list.push($bt.id),$l.set($bt.LS_TABS,$j.str($bt.list)),$bt._broadcast(),$bt.log($bt.list),$bt.zkillonload?$bt.zombkill(n):$.isFunc(n)&&n()},_dom:function(n,o,s,i,b,l){$bt.send({name:n,context:o,selector:s,data:i,callback:b,to:l?l:"*"})},_unload:function(){return $bt._refresh(),$bt._remove(),$l.set($bt.LS_TABS,$j.str($bt.list)),$bt._broadcast(),null},_focus:function(){$l.set($bt.LS_CURTAB,$bt.id)},_cmd:function(o){if($.isNone(o.originalEvent)||(o=o.originalEvent),o.key==$bt.LS_CMD){var n=$j.obj(o.newValue);if(n&&("*"==n.to||n.to==$bt.id)){$bt.log("RECEIVING cmd "+n.name+" : "),$bt.log(n);try{n.context=$.isNone(n.context)||null==n.context||$.isNone(window.parent.frames[n.context])?document:window.parent.frames[n.context].document}catch(o){$bt.log("bad context "+n.context+" : "+o.message)}switch($.isFunc($bt.before)&&$bt.before(n),n.name){case $bt.CMD_SYNC:$bt._refresh(),$bt.log($bt.list);break;case $bt.CMD_APPEND:$(n.selector,n.context).append(n.data);break;case $bt.CMD_HTML:$(n.selector,n.context).html(n.data);break;case $bt.CMD_RELOAD:window.location=$.isNone(n.url)?window.location:n.url;break;case $bt.CMD_ZOMBKILL:$bt._dontkill(n.askid,n.from);break;case $bt.CMD_DONTKILL:$bt.zomblist[""+n.askid]["ping"+n.from]="pong";break;default:$.isFunc($bt.on)&&$bt.on(n)}$.isStr(n.callback)&&n.callback.length>0&&!$.isNone($bt.callbacks[n.callback])&&$.isFunc($bt.callbacks[n.callback])&&($bt.log(n.callback),$bt.callbacks[n.callback].call({},n)),$.isFunc($bt.after)&&$bt.after(n)}}}};

View File

@ -3,7 +3,7 @@
* @contributors :
* @copyright : pluie.org
* @date : 2015-12-10 22:22:34
* @version : 0.6
* @version : 0.7
* @license : MIT
* @require : html5 localStorage svan (small vanilla jquery-like lib)
* @desc : manage communication between browser tabs
@ -33,7 +33,8 @@
* $bt.append('#test', "<b>it's cool to rewrite</b>", null, null, '1449974562012');
*
* // rewrite content to specified browser tab with callback
* $bt.html('#test', "<b>it's cool to rewrite</b>", null, function() { alert('callback'); }, '1449974562012');
* // callback must be define before command with method $bt.setCallback('callbackname', callback);
* $bt.html('#test', "<b>it's cool to rewrite</b>", null, 'callbackname', '1449974562012');
*
* // append content to specified browser tab on specific frame
* $bt.append('#test', "<b>it's cool to rewrite</b>", 'frameName', null, '1449974562012');
@ -42,7 +43,7 @@
* $bt.sync('#test');
*
* // perform a node synchro to specified browser tab on specific frame with callback
* $bt.sync('#test', 'frameName', callback, '1449974562012');
* $bt.sync('#test', 'frameName', 'callbackname', '1449974562012');
*
* // reload other browser tabs
* $bt.reload();
@ -74,9 +75,19 @@
* }
* }
*
* // it's also possible to define a before and after function :
* $bt.before = function(cmd) {
* $bt.log("i'm fired before every command");
* }
*
* $bt.after = function(cmd) {
* $bt.log("i'm fired after every command");
* }
*
* // send a custom command to other browser tabs
* $bt.send({ name : $bt.CMD_CUSTOM, customKey : 'customValue' });
*
*
* Bonus
*
* // alias localStorage : clear|rem|get|set
@ -106,7 +117,7 @@ var $j = (function alias() {
}());
var $bt = {
VERSION : 0.6,
VERSION : 0.7,
TRACE : true && !$.isNone(console),
/*! @constant LS_TABS localStorage key for browsertabs list */
LS_TABS : 'bt.list',
@ -132,6 +143,8 @@ var $bt = {
CMD_DONTKILL : 'bt.dontkill',
/*! @var vars */
vars : [],
/*! @var callbacks */
callbacks : [],
/*! @var zomblist */
zomblist : [],
/*! @var zkillonload */
@ -147,16 +160,24 @@ var $bt = {
init : function(fn) {
this._init(fn);
},
/*!
* @desc custom method to implements before custom command
* @public
* @method before
* @param string cmd a cmd to treat
*/
/*!
* @desc custom method to implements after custom command
* @public
* @method after
* @param string cmd a cmd to treat
*/
/*!
* @desc custom method to implements custom command
* @public
* @method on
* @param string cmd a cmd to treat
*/
on : function(cmd) {
// custom
this.log(cmd);
},
/*!
* @desc console log if trace is enabled
* @public
@ -188,10 +209,11 @@ var $bt = {
* @param string selector the selector wich target the node(s)
* @param string data the data to append
* @param string ctx context name of selector (frame name relative to document wich match specified selector) or if not defined or null current document
* @param string callback callback name to fire on command
* @param int btid target browser tab id (if not defined all target all tabs)
*/
append : function(selector, data, ctx, fn, btid) {
this._dom(this.CMD_APPEND, ctx, selector, data, fn, btid);
append : function(selector, data, ctx, callback, btid) {
this._dom(this.CMD_APPEND, ctx, selector, data, callback, btid);
},
/*!
* @desc perform a dom html command on other tabs
@ -200,10 +222,11 @@ var $bt = {
* @param string selector the selector wich target the node(s)
* @param string data the data to append
* @param string ctx context name of selector (frame name relative to document wich match specified selector) or if not defined or null current document
* @param string callback callback name to fire on command
* @param int btid target browser tab id (if not defined all target all tabs)
*/
html : function(selector, data, ctx, fn, btid) {
this._dom(this.CMD_HTML, ctx, selector, data, fn, btid);
html : function(selector, data, ctx, callback, btid) {
this._dom(this.CMD_HTML, ctx, selector, data, callback, btid);
},
/*!
* @desc perform a dom synchro command on other tabs
@ -211,11 +234,12 @@ var $bt = {
* @method sync
* @param string selector the selector wich target the node(s) to synchro
* @param string ctx context name of selector (frame name relative to document wich match specified selector) or if not defined or null current document
* @param string callback callback name to fire on command
* @param int btid target browser tab id (if not defined all target all tabs)
*/
sync : function(selector, ctx, fn, btid) {
sync : function(selector, ctx, callback, btid) {
var c = !$.isNone(ctx) && ctx != null ? parent.frames[ctx].document : document;
this._dom(this.CMD_HTML, ctx, selector, $(selector, c).html(), fn, btid);
this._dom(this.CMD_HTML, ctx, selector, $(selector, c).html(), callback, btid);
},
/*!
* @desc perform a reload command on other tabs with specified url
@ -227,6 +251,21 @@ var $bt = {
reload : function(url, btid) {
$bt.send({ name : $bt.CMD_RELOAD, url : url, to : !btid ? '*' : btid });
},
/*!
* @desc define a callback. callback are fire on desire command
* @public
* @method setCallback
* @param string name the callback name (for command binding)
* @param function callback the callback
*/
setCallback : function(name, callback) {
if ($.isNone($bt.callbacks[name])) {
$bt.callbacks[name] = callback;
}
else {
console.log("BT ERROR : callback name already exist");
}
},
/*!
* @desc kill all zombi tabs
* @public
@ -292,8 +331,8 @@ var $bt = {
}
},
/*! @private */
_dom : function(n, c, s, d, fn, id) {
$bt.send({ name : n, context : c, selector : s, data : d, fn : fn, to : !id ? '*' : id });
_dom : function(n, c, s, d, cb, id) {
$bt.send({ name : n, context : c, selector : s, data : d, callback : cb, to : !id ? '*' : id });
},
/*! @private */
_unload : function(e) {
@ -313,20 +352,19 @@ var $bt = {
if (e.key!=$bt.LS_CMD) return;
var cmd = $j.obj(e.newValue);
if (!cmd) return;
$bt.log('RECEIVING cmd '+cmd.name+' : ');
if (cmd.to == "*" || cmd.to == $bt.id) {
$bt.log("do "+cmd.name);
$bt.log('RECEIVING cmd '+cmd.name+' : ');
$bt.log(cmd);
try {
if (!$.isNone(cmd.context)) {
$bt.log(cmd.context);
if (!$.isNone(cmd.context) && cmd.context!=null && !$.isNone(window.parent.frames[cmd.context])) {
cmd.context = window.parent.frames[cmd.context].document;
$bt.log(cmd.context);
}
else cmd.context = document;
}
catch(e) {
$bt.log("bad context "+cmd.context+" : "+e.message);
}
if ($.isFunc($bt.before)) $bt.before(cmd);
switch(cmd.name) {
case $bt.CMD_SYNC :
@ -359,17 +397,13 @@ var $bt = {
default :
// do your stuff here
if ($.isFunc($bt.on)) $bt.on(cmd);
break;
}
if ($.isStr(cmd.fn) && cmd.fn.length>0) {
$bt.log(cmd.fn);
var f = eval("window."+cmd.fn);
if ($.isFunc(f)) {
f();
}
}
}
else {
$bt.log("ignoring (not target)");
if ($.isStr(cmd.callback) && cmd.callback.length>0 && !$.isNone($bt.callbacks[cmd.callback]) && $.isFunc($bt.callbacks[cmd.callback])) {
$bt.log(cmd.callback);
$bt.callbacks[cmd.callback].call({}, cmd);
}
if ($.isFunc($bt.after)) $bt.after(cmd);
}
}
}