这个部分主要是实现保存在浏览器本地存储 localStorage
源代码地址
//store模块
app.store = {
__store_key:'__sticky_note__',
get:function (id){
var notes = this.getNote();
return notes[id] || {};
},
set:function (id,content){
var notes = this.getNote();
if(notes[id]){
Object.assign(notes[id],content);
}else{
notes[id] = content;
}
localStorage[this.__store_key] = JSON.stringify(notes);
},
remove:function (id){
var notes = this.getNote();
delete notes[id];
localStorage[this.__store_key] = JSON.stringify(notes);
},
getNote:function (){
return JSON.parse(localStorage[this.__store_key] || '{}');
}
};
5、初始化
var notes = store.getNote();
Object.keys(notes).forEach(function(id){
var options = notes[id];
if(maxZIndex<options.zIndex){
maxZIndex=options.zIndex;
}
new createNote(Object.assign(options,{
id:id
}));
});
maxZIndex+=1;
6、保存
创建时保存
$('#create').addEventListener('click',function(e){
var note = new createNote({
left:Math.round(Math.random()*(window.innerWidth - 220)),
top:Math.round(Math.random()*(window.innerHeight - 320)),
zIndex: maxZIndex++,
});
note.save();
});
保存当前输入时间和内容
var editor = $('.editor',this.note);
var inputTimer;
var inputHandler = function (e){
var content = editor.innerHTML;
clearTimeout(inputTimer);
inputTimer = setTimeout(function (){
var time = Date.now()
store.set(this.note.id,{
content:content,
updateTime:time
});
this.updateTime(time);
}.bind(this),300);
}.bind(this);
editor.addEventListener('input',inputHandler);
createNote.prototype.save = function (){
store.set(this.note.id,{
left:this.note.offsetLeft,
top:this.note.offsetTop,
zIndex:parseInt(this.note.style.zIndex),
content:$('.editor',this.note).innerHTML,
updateTime:this.updateTimeInMS
});
}
mousedown的时候保存z-index的值
if(parseInt(moveNote.style.zIndex)!==maxZIndex - 1){
moveNote.style.zIndex = maxZIndex++;
store.set(moveNote.id,{
zIndex:maxZIndex-1
});
}
mouseuop的时候保存新的left和top值
store.set(moveNote.id,{
left:moveNote.offsetLeft,
top:moveNote.offsetTop
});
总结:主要学习了DOM、事件、原型、面向对象、模块化的知识点
所有的坚持都能被温柔以待!