Last active
August 29, 2015 14:02
-
-
Save imzjy/db18875e23a76eb19655 to your computer and use it in GitHub Desktop.
JQuery Plugin for poll message notification
This file contains hidden or 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
/* | |
JQuery Plugin for poll message from RESTful API | |
Usage: | |
[HTML] | |
<a href="javascript:void;" id="msgText"></a> | |
[JavaScript] | |
$('#msgText').pollMessage({ | |
'url': '/newmessage/get', | |
'duration': 10, | |
'click': function (msg) { | |
console.log(msg); | |
} | |
}).start(); | |
[Expected JSON] | |
{ | |
hasError [bool], | |
error [string], | |
data [string] | |
} | |
*/ | |
(function ($) { | |
$.fn.pollMessage = function (options) { | |
var isStop = false, | |
settings = {}, | |
curMessage = {} | |
that = this; | |
function _displayMessage(msg) { | |
if (!msg.hasError) { | |
that.html("你有" + msg.data + "条新消息"); | |
} else { | |
that.html("错误:" + msg.error); | |
} | |
} | |
function _poll() { | |
$.ajax({ | |
type: "GET", | |
url: settings.url, | |
cache: false, | |
success: function (jsonMsg) { | |
msg = $.parseJSON(jsonMsg); | |
curMessage = msg; | |
settings.newMessage.apply(that, [msg]); | |
if (!isStop) { | |
setTimeout(_poll, settings.duration * 1000); | |
} | |
}, | |
error: function (XMLHttpRequest, textStatus, errorThrown) { | |
settings.error.apply(that, [{ 'hasError': true, 'error': '无法连接', 'data': '' }]); | |
if (!isStop) { | |
setTimeout(_poll, settings.duration * 1000); | |
} | |
} | |
}); | |
} | |
function start() { | |
isStop = false; | |
setTimeout(_poll, 500); | |
} | |
function stop() { | |
isStop = true; | |
} | |
function setOptions(opts) { | |
settings = $.extend({ | |
'url': './Handlers/NewMessageHandler.ashx', | |
'duration': 5, | |
'newMessage': _displayMessage, | |
'error': _displayMessage, | |
'click': function(){} | |
}, options); | |
} | |
//init | |
setOptions(options); | |
that.click(function () { | |
settings.click.apply(that, [curMessage]); | |
return false; | |
}); | |
return { | |
'start': start, | |
'stop': stop, | |
'setOptions': setOptions | |
} | |
}; | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment