Skip to content

Instantly share code, notes, and snippets.

@CLCL
Created April 10, 2013 07:20
Show Gist options
  • Save CLCL/5352500 to your computer and use it in GitHub Desktop.
Save CLCL/5352500 to your computer and use it in GitHub Desktop.
/*
jQueryでアップロード進捗をAJAXで取得する的なの作るとき、
(いまどきはクライアントサイドで進捗取れるけどあえてAJAX)、
percentをプロパティに入れて管理したいんだけれども、コール
バック内だとthisが別人になるので、うまくいかない。
*/
var s = function(){
this.parcent = 0;
};
s.prototype = {
start: function() {
setTimeout( this.get , 1000 );
},
get: function() {
$.ajax({
type: "GET",
cache: false,
url: "/progress/123",
success: function(msg) {
this.percent = msg.percent; // thisが別人!
$("#parcent").html( this.percent );
}
});
if ( this.percent < 100 ) {
setTimeout( arguments.callee, 3000 );
}
},
};
$(function(){
$('#fileform').submit(function(){
var x = new s;
x.start();
});
});
/*
Function.bind()を使うと、thisを変えることができるけど、
Prototype.jsによるFunctionの拡張またはECMA5環境でしか
使えないので残念。
*/
var s = function(){
this.parcent = 0;
};
s.prototype = {
start: function() {
setTimeout( this.get , 1000 );
},
get: function() {
$.ajax({
type: "GET",
cache: false,
url: "/progress/123",
success: function(msg) {
this.percent = msg.percent;
$("#parcent").html( this.percent );
}.bind(this)
});
if ( this.percent < 100 ) {
setTimeout( arguments.callee, 3000 );
}
},
};
$(function(){
$('#fileform').submit(function(){
var x = new s;
x.start();
});
});
/*
jQueryなら、$.proxyがあるので、そっちを使う。
引数が複雑なので注意。
*/
var s = function(){
this.parcent = 0;
};
s.prototype = {
start: function() {
setTimeout( this.get , 1000 );
},
get: function() {
$.ajax({
type: "GET",
cache: false,
url: "/progress/123",
success: $.proxy(
function(msg) {
this.percent = msg.percent;
$("#parcent").html( this.percent );
},
this
)
});
if ( this.percent < 100 ) {
setTimeout( arguments.callee, 3000 );
}
},
};
$(function(){
$('#fileform').submit(function(){
var x = new s;
x.start();
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment