由于lz是从Sencha Touch转而开始原生Html5开发的,因此对于ST的MVC框架格外的喜欢那种将数据封装到store的做法,而backbone也借鉴了这种做法,因此我们可以使用backbone来实现sencha的那种model-store-view的做法,而这些数据都是存在于localstorage的,只要不要代码或者插件是无法清除的。
前提条件按照todo 的example配有backbone的框架以及引用backbone.localstorage.js
要实现存取首先我们在backbones来定义一个Model——InfoImg.js
define(function(require, exports, module){
var Backbone = require('backbone');
var InfoImg = Backbone.Model.extend({
// Default attributes for the todo item.
defaults: function() {
return {
Id: "0",
Created_at: (new Date()).format("yyyy-MM-dd hh:mm:ss"),
Retweeted_status: "resources/images/nodata.png",
Text:"亲,暂时没有数据哦",
Name:"CF西西工作室",
UserId:"-1"
};
},
// Ensure that each todo created has `title`.
initialize: function() {
if (!this.get("Id")) {
this.set({"Id": this.defaults().Id});
}
if (!this.get("Created_at")) {
this.set({"Created_at": this.defaults().Created_at});
}
if (!this.get("Retweeted_status")) {
this.set({"Retweeted_status": this.defaults().Retweeted_status});
}
if (!this.get("Text")) {
this.set({"Text": this.defaults().Text});
}
if (!this.get("Name")) {
this.set({"Name": this.defaults().Name});
}
if (!this.get("UserId")) {
this.set({"UserId": this.defaults().UserId});
}
}
});
module.exports = InfoImg;
});
其次我们定义一个collection(store)——InfoImgStore.js
/**
* Created with JetBrains WebStorm.
* User: ChenFeng
* Date: 13-4-27
* Time: 下午2:28
* To change this template use File | Settings | File Templates.
*/
define(function(require, exports, module){
var Backbone, InfoImg;
Backbone = require('backbone');
require('../libs/backbone.localStorage');
var $ = require('jquery');
var _ = require('underscore');
InfoImg = require('../model/InfoImg');
var InfoImgStore = Backbone.Collection.extend({
// Reference to this collection's model.
model: InfoImg,
// Save all of the todo items under the `"todos-backbone"` namespace.
localStorage: new Backbone.LocalStorage("cfxixi-XiXiInfo-Img"),
// Filter down the list of all todo items that are finished.
done: function() {
return this.filter(function(todo){ return todo.get('Id'); });
},
// Filter down the list to only todo items that are still not finished.
remaining: function() {
return this.without.apply(this, this.done());
}
});
module.exports = new InfoImgStore();
})
然后就是在框架中调用了:
调用时需要引用:
存数据时用法:
var weiboStore = require('../store/InfoImgStore')
存数据时用法:
weiboStore.create({id:imgId,Created_at:imgCreated_at,Retweeted_status:imgUrl,
Text:imgText,Name:imgName,UserId:userId});
取数据时:
weiboStore.localStorage.find({id:'3628622776303138'});
取出全部时:
weiboStore.localStorage.find({id:'3628622776303138'});
如此就便能实现对localstorge的轻松操作了