我从这篇文章中找到的代码开始:http ://www.bennadel.com/blog/2171-Realtime-Messaging-And-Synchronization-With-NowJS-And-Node-js.htm 。
我尝试重构 html,以便该示例使用 jQuery UI Draggable。代码粘贴在下面;服务器端不变。它工作正常,但拖动时存在闪烁问题。我认为这是一个 jQuery 问题,尽管我在想服务器端的过滤可能有问题?
另外,我想知道如何创建一个“initialPosition”函数,以便打开一个新页面会将可拖动的 div 放在正确的位置。我认为这是需要在服务器端完成的事情,理想情况下它将来自在拖动结束后写入的数据库值。
此外,除此之外,我想知道如果页面上有多个可拖动项目,代码会是什么样子。
HTML
<!DOCTYPE html>
<html>
<head>
<title>NowJS Draggable using jQuery UI</title>
<style type="text/css">
html, body { height: 100%; width: 100%; overflow: hidden; }
#draggable { width: 150px; height: 150px; border: 1px solid black; }
</style>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"/></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.min.js"/></script>
<script type="text/javascript" src="/nowjs/now.js"></script>
<script>
$(function() {
$( "#draggable" ).draggable();
$( "#draggable" ).bind( "drag", function( event ) {
var newPosition = {
left: ( event.pageX ),
top: ( event.pageY ),
};
now.syncPosition( newPosition );
});
now.updatePosition = function( newPosition ){
$( "#draggable" ).css( newPosition );
};
});
</script>
</head>
<body>
<div id="draggable"></div>
</body>
</html>
NODE.JS(删除注释)
var sys = require( "sys" );
var http = require( "http" );
var url = require( "url" );
var path = require( "path" );
var fileSystem = require( "fs" );
var server = http.createServer(
function( request, response ){
fileSystem.readFile(
__dirname+'/index.html',
"binary",
function( error, fileBinary ){
if (error){
response.writeHead( 404 );
response.end();
return;
}
response.writeHead( 200 );
response.write( fileBinary, "binary" );
response.end();
}
);
}
);
server.listen( 8080 );
(function(){
var nowjs = require( "now" );
var everyone = nowjs.initialize( server );
var primaryKey = 0;
everyone.connected(
function(){
this.now.uuid = ++primaryKey;
}
);
everyone.now.syncPosition = function( position ){
everyone.now.filterUpdateBroadcast( this.now.uuid, position );
};
everyone.now.filterUpdateBroadcast = function( masterUUID, position ){
if (this.now.uuid == masterUUID){
return;
}
everyone.now.updatePosition( position );
};
})();
sys.puts( "Server is running on 8080" );