Naisao sam jedan problem koji nisam imao ranije jer nisam koristio javascript na ovaj nacin(neka ovakva objektna notacija)
Evo koda posto se tu lepse vidi
Problem je sto kad setInterval pozove ovu clock funkciju this ne upucuje na myObj nego na window,
pa je normalno this.state undefined.
E sad, kako ovo resiti..
Evo koda posto se tu lepse vidi
Code:
$(document).ready(function(){
var myObj = function() { };
myObj.prototype = {
init: function(options){
var defaults ={
speed:1000,
increment: 1
};
this.state ={
started: false,
timer: 0,
interval: 0,
counter: 0
};
this.options = $.extend({}, defaults, options);
},
clock: function(){
this.state.timer+=1;
},
start : function(){
this.state.interval = setInterval(this.clock, this.options.speed);
},
stop : function(){
clearInterval(this.state.interval);
}
};
o = new myObj();
o.init({speed:2000});
o.start();
});
$(document).ready(function(){
var myObj = function() { };
myObj.prototype = {
init: function(options){
var defaults ={
speed:1000,
increment: 1
};
this.state ={
started: false,
timer: 0,
interval: 0,
counter: 0
};
this.options = $.extend({}, defaults, options);
},
clock: function(){
this.state.timer+=1;
},
start : function(){
this.state.interval = setInterval(this.clock, this.options.speed);
},
stop : function(){
clearInterval(this.state.interval);
}
};
o = new myObj();
o.init({speed:2000});
o.start();
});
Problem je sto kad setInterval pozove ovu clock funkciju this ne upucuje na myObj nego na window,
pa je normalno this.state undefined.
E sad, kako ovo resiti..