How to create list-item “Add to favorite” (localstorage) option in Framrework7?
plz help this issue…anyone can help me with code?
var obj={
name:'favorite',
get:function(){
return JSON.parse(localStorage.getItem(this.name)||'[]');
},
set:function(arr){
localStorage.setItem(this.name,JSON.stringify(arr));
},
add:function(o){
var arr=this.get();
arr.push(o);
this.set(arr);
},
del:function(o){
this.set(this.get().filter(function(i){return i.id != o.id;}));
}
};
console.log(obj.get()); // -> []
obj.add({id:'1',name:'name 1'});
console.log(obj.get()); // -> [{id:'1',name:'name 1'}]
obj.add({id:'2',name:'name 2'});
console.log(obj.get()); // -> [{id:'1',name:'name 1'},{id:'2',name:'name 2'}]
obj.del({id:'1'});
console.log(obj.get()); // -> [{id:'2',name:'name 2'}]
obj.del({id:'2'});
console.log(obj.get()); // -> []
“add”: this.del(o) before arr.push(o) or check unique.
thanks,
if possible plz give me html bcoz im beginner
ok
later i will try to do something
just tell me if it should be with => component || template || plain html
longer than i thought
- go to https://framework7.io/kitchen-sink/core/
- open console
- copy/paste this code
- click on items
- refresh & repeat
app.views.current.routes.unshift({
path:'/some-page/',
component:{
template:`
<div class="page">
<div class="navbar">
<div class="navbar-inner">
<div class="title">{{title}}</div>
</div>
</div>
<div class="page-content">
<div class="list">
<ul>
{{#items}}
<li>
<a href="#" class="item-link item-content"
data-context=\'{{js 'return JSON.stringify(this)'}}\'>
<div class="item-inner">
<div class="item-title">{{name}}</div>
<div class="item-after">{{#if status}}OK{{/if}}</div>
</div>
</a>
</li>
{{/items}}
</ul>
</div>
</div>
</div>
`,
data:function(){
return {
LSname:'favorite',
title:'Add to Favorite',
items:[
{id:'1',name:'name 1'},{id:'2',name:'name 2'},{id:'3',name:'name 3'},
{id:'4',name:'name 4'},{id:'5',name:'name 5'},{id:'6',name:'name 6'}
]
}
},
methods:{
get:function(){
return JSON.parse(localStorage.getItem(this.LSname)||'[]');
},
set:function(arr){
localStorage.setItem(this.LSname,JSON.stringify(arr));
},
add:function(o){
var arr=this.get();
arr.push(o);
this.set(arr);
},
del:function(o){
this.set(this.get().filter(function(i){return i.id != o.id;}));
},
update:function(){
var self=this;
self.items.map(function(i){
i.method='add';
i.status=false;
self.get().map(function(l){
i.method=(i.id == l.id)?'del':i.method;
i.status=(i.id == l.id)?true:i.status;
});
});
self.$setState({items:self.items});
}
},
on:{
pageInit:function(e,page){
var self=this;
self.update();
page.$el.on('click','.item-link',function(e){
var context=JSON.parse(self.$(this).attr('data-context'));
self[context.method](context);
self.update();
});
}
}
}
});
app.views.current.router.navigate('/some-page/');