【发布时间】:2011-03-06 11:23:34
【问题描述】:
我正在尝试使用 jQuery 和 jQueryUI 的 datepicker 内联模式让事情正常工作。
我想将我的所有代码放在一个全局对象中,并将其用于 datepicker 初始化函数(beforeShowDay、changeMonthYear)。 我还有一些实用功能。
我被卡住了,因为我真的不知道如何继续。
我已经阅读了很多文章、教程、stackoverflow 线程——尤其是在 this 范围等方面,但现在我不知道从哪里开始!
这是我目前所拥有的:
var Calendar = (function() {
var obj = this;
var calendar = {
datescache: [],
bsd: function (date) {
var offset = this.formatNum(date.getMonth()+1)+'-'+this.formatNum(date.getDate());
if (thedate[offset] != undefined) {
return [true, 'bold', thedate[offset] + ' événement(s)'];
} else {
return [true];
}
},
formatNum: function (i) {return ('0'+i).slice(-2);},
getEventsForDate: function(year, month, inst) {
var date = this.datescache;
if (this.datescache[month] === undefined) {
console.warn('uncached: '+month);
$.ajax({
url: '/event/get-event-count/year/'+year+'/month/'+month+'/format/json',
success: function (resp) {
date[month] = resp.events;
},
async: false
});
}
console.log('return: '+month);
return date[month];
}
}
return calendar;
})();
$('#calendar').datepicker({
dateFormat: "dd\/mm\/yy",
showOtherMonths: true,
selectOtherMonths: true,
beforeShowDay: Calendar.bsd,
onChangeMonthYear: Calendar.getEventsForDate,
});
当然我在这行有一个错误:
var offset = this.formatNum(date.getMonth()+1)+'-'+this.formatNum(date.getDate());
因为this指的是日期选择器对象,因为我们在一个回调函数beforeShowDay中,它负责将日期选择器实例作为this传递给函数。
但我需要this 来引用我的实用函数,例如formatNum。
- 我应该从哪里开始?
- 尝试扩展
datepicker对象是否更好(尚未尝试)?
提前感谢您的帮助!
编辑 1
好的,有了更多的阅读和第一个答案,我设法得到了一些工作:
var Calendar = (function() {
var calendar = function() {
var self = this;
this.datescache = [];
this.bsd = function (date) {
[[... I use for instance self.datescache ... ]]
}
[[...]]
};
return new calendar();
})();
这似乎工作正常。
- 还需要全局封装吗?
再次感谢!
【问题讨论】:
标签: javascript jquery jquery-ui scope