Backbone Backbone-localStorage demo
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="lib/json2.js"></script> <script src="lib/jquery-latest.js"></script> <script src="lib/underscore.js"></script> <script src="lib/backbone.js"></script> <script src="lib/backbone.localStorage.js"></script> </head> <body> <style> span{display: block;} </style> <p id="app"></p> <button id="btn">Click</button> <script src="js/demo.js"></script> </body> </html>
js:
var DemoModel = Backbone.Model.extend({ defaults: { name: "King-fly", age: 23 } }); var DemoCollection = Backbone.Collection.extend({ model: DemoModel, localStorage: new Backbone.LocalStorage("Demotodo"), initialize: function() { this.on("add", this.triAdd); }, triAdd: function() { console.log("DemoCollection add method"); }, done: function(name) { return this.where({name: name}) } }); var demoCollection = new DemoCollection; var SpanView = Backbone.View.extend({ tagName: "span", initialize: function() { this.render(); this.$el.bind("click",this.clear); this.listenTo(this.model, "destroy", this.remove) }, render: function() { this.$el.html(_.template("My name is <%= name %>,my age is <%= age %>", this.model.toJSON())); return this; }, clear: function() { this.remove(); console.dir(this); } }); var DemoView = Backbone.View.extend({ el: "body", counter: 0, events: { "click button#btn": "btnClick", "click button#clear": "clearData" }, initialize: function() { this.listenTo(demoCollection, "add", this.addOne); // this.listenTo(demoCollection, "") demoCollection.fetch(); }, clearData: function() { _.invoke(demoCollection.done("Wuhan"), "destroy"); }, render: function() { }, btnClick: function() { demoCollection.create({name: "Wuhan", age: 23 + this.counter++}); }, addOne: function(demoModel) { var view = new SpanView({model: demoModel}) $("#app").append(view.render().el); }, addAll: function() { demoCollection.each(this.addOne, this); } }) var demoView = new DemoView();
Backbone 应用的关键点是要理清需求的流程,每个View 层的操作对象都有自己的执行逻辑, 理解各View层之间的关系对处理Model层来说至关重要。而作为数据的操作层Collection来说,起相关联数据所展现的复杂度随着view层的增加不断增加。因此控制好collection层显得至关重要。
由于Backbone 是基于Underscore库为基础的,作为函数库的underscore需要更深层次的了解。
posted on 2013-12-29 17:43 Ijavascript 阅读(376) 评论(0) 编辑 收藏 举报