Created
November 18, 2012 23:33
-
-
Save felipegtx/4108148 to your computer and use it in GitHub Desktop.
Gerenciador de assinaturas JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <reference path="../jQueryMin.js" /> | |
(function (window) { | |
var miniRT = (function () { | |
var configuracoesBasicas = { | |
nomePlugin: "Default", | |
intervalo: 5000, | |
iniciarAutomaticamente: true, | |
/// Delegates | |
mensagemNova: function (data/*, textStatus, jqXHR*/) { return { parar: false }; }, | |
erro: function (data/*, textStatus, errorThrown*/) { return { parar: false }; }, | |
desconectado: function () { }, | |
conectado: function () { }, | |
reconectado: function () { }, | |
/// Configurações da fonte e tipo de dados esperados para a assinatura | |
/// (Apenas as seguintes features são configuráveis de forma garantida) | |
dadosAssinatura: { | |
url: "", | |
cache: false, | |
async: true, | |
type: 'post', | |
dataType: 'json', | |
data: {} | |
} | |
}; | |
var id = 1; | |
var _pluginController = { | |
Plugins: {}, | |
Registrar: function (rtF) { | |
var rt = new rtF(); | |
var nomePlugin = rt.Nome(); | |
if (!this.Contem(nomePlugin)) { | |
this.Plugins[nomePlugin] = rtF; | |
} | |
}, | |
Carregar: function (strNomePlugin, params) { | |
if (this.Contem(strNomePlugin)) { | |
var plugin = new this.Plugins[strNomePlugin]; | |
plugin.Carregar(params); | |
plugin.Id = ++id; | |
return plugin; | |
} | |
}, | |
Contem: function (strNomePlugin) { | |
for (plugin in this.Plugins) { | |
if (plugin === strNomePlugin) { return true; } | |
} | |
return false; | |
} | |
}; | |
/// Template (formato) básico de um plugin | |
var RTTemplate = function () { | |
this.Id = 0, | |
this.Nome = function () { return "Template"; }; | |
this.Carregar = function (params) { /* 'Equivalente' ao construtor */ }; | |
this.Parar = function () { return this; }; | |
this.Pausar = function () { return this; }; | |
this.Iniciar = function () { return this; }; | |
}; | |
var membrosPublicos = { | |
CarregarRT: function (rt) { | |
if (rt) { | |
_pluginController.Registrar(rt); | |
} | |
return this; | |
}, | |
Assinar: function (params) { | |
var paramsValidos = $.extend({}, configuracoesBasicas, params); | |
paramsValidos.dadosAssinatura = $.extend({}, configuracoesBasicas.dadosAssinatura, params.dadosAssinatura); | |
if (paramsValidos.nomePlugin === "") { return paramsValidos.erro("O nome do plugin que será executado não foi definido"); } | |
if (!_pluginController.Contem(paramsValidos.nomePlugin)) { return paramsValidos.erro("O plugin '" + paramsValidos.nomePlugin + "' não está registrado."); } | |
if (paramsValidos.dadosAssinatura.url === "") { return paramsValidos.erro("Endpoint da assinatura não pode estar vazio!"); } | |
return _pluginController.Carregar(paramsValidos.nomePlugin, paramsValidos); | |
} | |
}; | |
/// Carregamento do plugin padrão que utiliza ajax+jquery para visitas periódicas ao | |
/// endpoint desejado | |
membrosPublicos.CarregarRT(function () { | |
var configuracoes = { interromperExecucao: false, executar: false, intervaloAssinatura: 5000, dadosAssinatura: {} }; | |
var feedback = { executando: false, connectado: false, inicializado: false }; | |
var timeouts = { assinatura: null }; | |
function EntregarMensagens() { | |
return !configuracoes.interromperExecucao && configuracoes.executar; | |
} | |
function _(oQue) { | |
/// <summary> | |
/// Executa um delegate qualquer de forma que o resultado desta operação não afete o | |
/// comportamente do componente como um todo | |
/// </summary> | |
try { oQue(); } catch (e) { } | |
} | |
function IniciarTimeouts() { | |
/// <summary> | |
/// Gerencia execução principal das idas ao servidor em seus possíveis momentos | |
/// </summary> | |
if (!feedback.executando) { | |
if (timeouts.assinatura != null) { window.clearTimeout(timeouts.assinatura); } | |
if (configuracoes.executar) { | |
feedback.executando = true; | |
$.ajax(configuracoes.dadosAssinatura); | |
} | |
} | |
} | |
return { | |
Nome: function () { return "Default"; }, | |
Carregar: function (params) { | |
configuracoes.dadosAssinatura = params.dadosAssinatura; | |
configuracoes.executar = params.iniciarAutomaticamente; | |
configuracoes.intervaloAssinatura = params.intervalo; | |
params.dadosAssinatura.complete = function () { | |
/// <summary> | |
/// Delegate para reagendamento da assinatura (se for o caso) | |
/// </summary> | |
feedback.executando = false; | |
if (EntregarMensagens()) { | |
if (!configuracoes.interromperExecucao) { | |
timeouts.assinatura = window.setTimeout(IniciarTimeouts, configuracoes.intervaloAssinatura); | |
timeouts.assinatura = null; | |
} | |
} | |
} | |
params.dadosAssinatura.error = function (a, b, c) { | |
/// <summary> | |
/// Delegate para gerenciamento de erros decorrentes da execução da assinatura | |
/// </summary> | |
if (EntregarMensagens()) { | |
if (a.status === 404) { | |
feedback.connectado = false; | |
_(params.desconectado); | |
} | |
else { | |
_(function () { | |
result = params.erro(a, b, c); | |
if ((result) && result.parar) { | |
configuracoes.interromperExecucao = true; | |
configuracoes.executar = false; | |
} | |
}); | |
} | |
} | |
}; | |
params.dadosAssinatura.success = function (a, b, c) { | |
/// <summary> | |
/// Delegate para gerenciamento do resultado da execução de uma assinatura que | |
/// conseguiu retornar dados do servidor | |
/// </summary> | |
if (EntregarMensagens()) { | |
if (!feedback.connectado) { | |
if (feedback.inicializado) { | |
_(params.reconectado); | |
} else { | |
_(params.conectado); | |
} | |
feedback.connectado = true; | |
} | |
feedback.inicializado |= true; | |
_(function () { | |
var result = params.mensagemNova(a, b, c); | |
if ((result) && result.parar) { | |
configuracoes.interromperExecucao = true; | |
configuracoes.executar = false; | |
} | |
}); | |
} | |
}; | |
if (configuracoes.executar) { | |
IniciarTimeouts(); | |
} | |
}, | |
Parar: function () { | |
configuracoes.interromperExecucao = true; | |
return this; | |
}, | |
Pausar: function () { | |
configuracoes.executar = false; | |
return this; | |
}, | |
Parado: function () { return configuracoes.interromperExecucao; }, | |
Pausado: function () { return configuracoes.executar; }, | |
Iniciar: function () { | |
configuracoes.interromperExecucao = false; | |
configuracoes.executar = true; | |
IniciarTimeouts(); | |
return this; | |
} | |
}; | |
}); | |
/// Retornamos nossos membros públicos para consumo | |
return membrosPublicos; | |
})(); | |
$.extend(window, { miniRT : miniRT }); | |
})(window); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html> | |
<head> | |
<title>MiniRT</title> | |
</head> | |
<body> | |
<div id="msgs"> | |
<b>Mensagens:</b> | |
<hr size="1" /> | |
</div> | |
<script src="jQuery.js" type="text/javascript"></script> | |
<script src="miniRT.js" type="text/javascript"></script> | |
<script type="text/javascript" language="javascript"> | |
function Escrever(strTexto){ | |
$("#msgs").html($("#msgs").html() + "- " + strTexto + "<br/>"); | |
} | |
var t1 = window.miniRT.Assinar({ | |
dadosAssinatura: { | |
url: "teste.txt", | |
type: 'get' | |
}, | |
iniciarAutomaticamente: false, | |
mensagemNova: function (obj) { | |
Escrever(obj.Mensagem); | |
}, | |
desconectado: function () { | |
Escrever("Ops.. Parece que seu recurso está indisponível no momento."); | |
}, | |
reconectado: function () { | |
Escrever("Voltamos! :) "); | |
}, | |
conectado: function () { | |
Escrever("Conectado com sucesso!"); | |
}, | |
erro: function (mensagem) { | |
Escrever("Algo deu muito errado - " + mensagem.statusText); | |
} | |
}); | |
window.setTimeout(t1.Iniciar, 3000); | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
miniRT.Assinar({ | |
dadosAssinatura:{ | |
url:"/feed" | |
}, | |
mensagemNova:function(msg){ | |
alert('mensagem'); | |
return {parar:true}; | |
}, | |
desconectado:function(){ alert("Ops.. parece que você está passando por problemas de conexão. Aguente um pouco enquanto tentamos obter os dados novamente."); } | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment