Sunday 15 June 2014

javascript - Making my LiveTime object literal -



javascript - Making my LiveTime object literal -

this code used have, worked fine:

var todaytime = new date(); (function updateclock() { todaytime.settime(todaytime.valueof() + 1000); // in 2 digit format. document.getelementbyid("hours").innerhtml = ("0" + todaytime.gethours()).slice(-2); document.getelementbyid("minutes").innerhtml = ("0" + todaytime.getminutes()).slice(-2); document.getelementbyid("seconds").innerhtml = ("0" + todaytime.getseconds()).slice(-2); settimeout(updateclock, 1000); })();

i attempted changed object literal can interact in improve way.

what i'm trying here have start() execute automatically when livetime object defined.

also need maintain track of timeout id can utilize whenever i'm calling stop() method.

var livetime = { element: document.getelementbyid("current-time"), date: new date(), timeoutid: 0, start: (function() { livetime.timeoutid = settimeout(function() { livetime.date.settime(livetime.date.valueof() + 1000); livetime.element.innerhtml = ("0" + livetime.date.gethours()).slice(-2) + ":" + ("0" + livetime.date.getminutes()).slice(-2) + ":" + ("0" + livetime.date.getseconds()).slice(-2); }, 1000); })(), stop: function() { cleartimeout(livetime.timeoutid); } }

unfortunately code giving me bunch of undefined errors.

uncaught typeerror: cannot set property 'date' of undefined

what doing wrong, , how can prepare , else that's wrong code?

you defining start self executing function. means when livetime object beingness created, start set result of function. since function running while livetime still beingness created, livetime undefined. alter start definition to

start: function() { livetime.timeoutid = settimeout(function() { livetime.date.settime(livetime.date.valueof() + 1000); livetime.element.innerhtml = ("0" + livetime.date.gethours()).slice(-2) + ":" + ("0" + livetime.date.getminutes()).slice(-2) + ":" + ("0" + livetime.date.getseconds()).slice(-2); }, 1000); },

and should work (this still code, did not check other errors may there)

javascript oop object-literal

No comments:

Post a Comment