1 var AbstractView = _.inherit({ 2 propertys: function () { 3 this.$el = $('#main'); .events = {}; 6 }, 7 initialize: function (opts) { .propertys(); 10 }, 11 $: function (selector) { .$el.find(selector); 13 }, 14 show: function () { 15 this.$el.show(); 16 this.bindEvents(); 17 }, 18 bindEvents: function () { 19 var events = this.events; (!(events || (events = _.result(this, 'events')))) return this; 22 this.unBindEvents(); delegateEventSplitter = /^(\S+)\s*(.*)$/; 26 var key, method, match, eventName, selector; (key in events) { 30 method = events[key]; 31 if (!_.isFunction(method)) method = this[events[key]]; 32 if (!method) continue; 33 34 match = key.match(delegateEventSplitter); 35 eventName = match[1], selector = match[2]; 36 method = _.bind(method, this); 37 eventName += '.delegateUIEvents' + this.id; (selector === '') { 40 this.$el.on(eventName, method); 41 } else { 42 this.$el.on(eventName, selector, method); 43 } 44 } ; 46 }, 47 48 unBindEvents: function () { 49 this.$el.off('.delegateUIEvents' + this.id); ; 51 } 52 53 });
View的基类View = _.inherit(AbstractView, { 3 propertys: function ($super) { 4 $super(); 5 this.$el = $('#main'); .events = { 9 'click .js_add': 'blogAddAction', 10 'click .js_blog_del': 'blogDeleteAction' 11 }; .model = new Model({ 16 scope: this, 17 controllers: { 18 numController: this.numController, 19 typeController: this.typeController, 20 labelController: this.labelController, 21 blogsController: this.blogsController 22 } 23 }); 24 }, numController: function () { 27 this.$('.js_num').html(this.model.getNum()); 28 }, typeController: function () { 31 var html = ''; 32 var tpl = document.getElementById('js_tpl_kv').innerHTML; 33 var data = this.model.getTypeInfo(); 34 html = _.template(tpl)({ objs: data }); 35 this.$('.js_type_wrapper').html(html); }, labelController: function () { html = ''; 43 var tpl = document.getElementById('js_tpl_kv').innerHTML; 44 var data = this.model.getLabelInfo(); 45 html = _.template(tpl)({ objs: data }); 46 this.$('.js_label_wrapper').html(html); 47 48 }, blogsController: function () { 51 console.log(this.model.get()); 52 var html = ''; 53 var tpl = document.getElementById('js_tpl_blogs').innerHTML; 54 var data = this.model.get(); 55 html = _.template(tpl)(data); 56 this.$('.js_blogs_wrapper').html(html); 57 }, blogAddAction: function () { .model.add( 63 this.$('.js_title').val(), 64 this.$('.js_type').val(), 65 this.$('.js_label').val() 66 ); 67 68 }, 69 blogDeleteAction: function (e) { 70 var el = $(e.currentTarget); 71 this.model.remove(el.attr('data-id')); 72 } 73 }); view = new View(); 76 view.show();
完整代码&示例