1 define([], function () { 2 'use strict'; _.inherit({ 5 6 propertys: function () { .$el = null; .selector = ''; .view = null; .template = ''; .events = {}; .entity = null; 24 }, 25 26 setOption: function (options) { (var k in options) { 29 if (k == 'events') { 30 _.extend(this[k], options[k]); 31 continue; 32 } 33 this[k] = options[k]; 34 } }, initData: function () { 40 }, initWrapper: function (el) { 44 if (el && el[0]) { 45 this.$el = el; 46 return; 47 } 48 this.$el = this.view.$(this.selector); 49 }, 50 51 initialize: function (opts) { .propertys(); .setOption(opts); 57 this.initData(); .initWithoutRender(); 60 61 }, initWithoutRender: function () { 65 if (this.template) return; 66 var scope = this; 67 this.view.on('onShow', function () { 68 scope.initWrapper(); 69 if (!scope.$el[0]) return; (!scope.view) return; 72 scope.initElement(); 73 scope.bindEvents(); 74 }); 75 }, 76 77 $: function (selector) { .$el.find(selector); 79 }, initElement: function () { }, getViewModel: function () { 87 throw '必须重写'; 88 }, 89 90 _render: function (callback) { 91 var data = this.getViewModel() || {}; 92 var html = this.template; 93 if (!this.template) return ''; (_.isFunction(this.template)) { 96 html = this.template(data); 97 } else { 98 html = _.template(this.template)(data); 99 } 100 typeof callback == 'function' && callback.call(this); 101 return html; 102 }, render: function () { 106 this.initWrapper(); 107 if (!this.$el[0]) return; (!this.view) return; html = this._render(); 113 this.$el.html(html); 114 this.initElement(); 115 this.bindEvents(); 116 117 }, 118 119 bindEvents: function () { 120 var events = this.events; (!(events || (events = _.result(this, 'events')))) return this; 123 this.unBindEvents(); delegateEventSplitter = /^(\S+)\s*(.*)$/; 127 var key, method, match, eventName, selector; (key in events) { 131 method = events[key]; 132 if (!_.isFunction(method)) method = this[events[key]]; 133 if (!method) continue; 134 135 match = key.match(delegateEventSplitter); 136 eventName = match[1], selector = match[2]; 137 method = _.bind(method, this); 138 eventName += '.delegateUIEvents' + this.id; (selector === '') { 141 this.$el.on(eventName, method); 142 } else { 143 this.$el.on(eventName, selector, method); 144 } 145 } ; 148 }, 149 150 unBindEvents: function () { 151 this.$el.off('.delegateUIEvents' + this.id); ; 153 } 154 }); 155 156 });
module.view 数据实体类这里的数据实体对应着,MVC中的Model,因为之前已经使用model用作了数据请求相关的命名,这里便使用Entity做该工作: