我正在尝试使用模块模式构建我的Javascript。
var appTest = {
settings: {
date : $(".date")
},
init: function() {
s = this.settings;
this.setDate();
},
setDate: function() {
var monthNames = [ "January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December" ];
var dt = new Date();
s.date.html(dt.getDate()+" "+monthNames[dt.getMonth()]+" "+dt.getFullYear());
//$(".date").html(dt.getDate()+" "+monthNames[dt.getMonth()]+" "+dt.getFullYear());
}
};
$(function(){
appTest.init();
});
现在,带有.date类的dom元素不会使用新日期进行更新。但是,如果我取消注释被注释的行,它就可以正常工作。
我仍在努力寻找Javascript的方法。
答案 0 :(得分:2)
您模块中的一些问题:
s
,但没有声明它并且存在名称冲突的风险。你应该嵌入它setDate
你可以解决这些问题:
var appTest = (function(){
var monthNames = [ "January", "February", "March", "April", "May", "June","July", "August", "September", "October", "November", "December" ];
var settings = {}; // this is private (not visible from outside the module)
var module = {};
module.init = function() {
settings.date = $(".date");
module.setDate();
};
module.setDate = function() {
var dt = new Date();
settings.date.html(dt.getDate()+" "+monthNames[dt.getMonth()]+" "+dt.getFullYear());
};
return module;
})();
$(function(){
appTest.init();
});
答案 1 :(得分:0)
我建议使用原型。你可以制作一个像:
这样的单身人士var App = (function AppModule() {
function App() {
// All your options here
this.$date = $('.date');
this.init(); // initialize singleton
}
App.prototype = {
init: function() {
this.setDate();
},
setDate: function() {
var months = [...]
, monthsdate = new Date;
this.$date.html(...);
}
};
return new App; // a singleton
}());