compiler.js 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. var config = require('./config'),
  2. ViewModel = require('./viewmodel'),
  3. Binding = require('./binding'),
  4. DirectiveParser = require('./directive-parser'),
  5. TextParser = require('./text-parser'),
  6. depsParser = require('./deps-parser'),
  7. eventbus = require('./utils').eventbus
  8. var slice = Array.prototype.slice,
  9. ctrlAttr = config.prefix + '-controller',
  10. eachAttr = config.prefix + '-each'
  11. /*
  12. * The DOM compiler
  13. * scans a DOM node and compile bindings for a ViewModel
  14. */
  15. function Compiler (el, options) {
  16. config.log('\ncreated new Compiler instance.\n')
  17. if (typeof el === 'string') {
  18. el = document.querySelector(el)
  19. }
  20. this.el = el
  21. el.compiler = this
  22. this.bindings = {}
  23. this.directives = []
  24. this.watchers = {}
  25. this.listeners = []
  26. // list of computed properties that need to parse dependencies for
  27. this.computed = []
  28. // list of bindings that has dynamic context dependencies
  29. this.contextBindings = []
  30. // copy options
  31. options = options || {}
  32. for (var op in options) {
  33. this[op] = options[op]
  34. }
  35. // check if there's passed in data
  36. var dataAttr = config.prefix + '-data',
  37. dataId = el.getAttribute(dataAttr),
  38. data = (options && options.data) || config.datum[dataId]
  39. if (dataId && !data) {
  40. config.warn('data "' + dataId + '" is not defined.')
  41. }
  42. data = data || {}
  43. el.removeAttribute(dataAttr)
  44. // if the passed in data is the viewmodel of a Compiler instance,
  45. // make a copy from it
  46. if (data instanceof ViewModel) {
  47. data = data.$dump()
  48. }
  49. // check if there is a controller associated with this compiler
  50. var ctrlID = el.getAttribute(ctrlAttr), controller
  51. if (ctrlID) {
  52. el.removeAttribute(ctrlAttr)
  53. controller = config.controllers[ctrlID]
  54. if (controller) {
  55. this.controller = controller
  56. } else {
  57. config.warn('controller "' + ctrlID + '" is not defined.')
  58. }
  59. }
  60. // create the viewmodel object
  61. // if the controller has an extended viewmodel contructor, use it;
  62. // otherwise, use the original viewmodel constructor.
  63. var VMCtor = (controller && controller.ExtendedVM) || ViewModel,
  64. viewmodel = this.vm = new VMCtor(this, options)
  65. // copy data
  66. for (var key in data) {
  67. viewmodel[key] = data[key]
  68. }
  69. // apply controller initialize function
  70. if (controller && controller.init) {
  71. controller.init.call(viewmodel)
  72. }
  73. // now parse the DOM
  74. this.compileNode(el, true)
  75. // for anything in viewmodel but not binded in DOM, create bindings for them
  76. for (key in viewmodel) {
  77. if (key.charAt(0) !== '$' && !this.bindings[key]) {
  78. this.createBinding(key)
  79. }
  80. }
  81. // extract dependencies for computed properties
  82. if (this.computed.length) depsParser.parse(this.computed)
  83. this.computed = null
  84. // extract dependencies for computed properties with dynamic context
  85. if (this.contextBindings.length) this.bindContexts(this.contextBindings)
  86. this.contextBindings = null
  87. }
  88. // for better compression
  89. var CompilerProto = Compiler.prototype
  90. /*
  91. * Compile a DOM node (recursive)
  92. */
  93. CompilerProto.compileNode = function (node, root) {
  94. var compiler = this
  95. if (node.nodeType === 3) { // text node
  96. compiler.compileTextNode(node)
  97. } else if (node.nodeType === 1) {
  98. var eachExp = node.getAttribute(eachAttr),
  99. ctrlExp = node.getAttribute(ctrlAttr),
  100. directive
  101. if (eachExp) { // each block
  102. directive = DirectiveParser.parse(eachAttr, eachExp)
  103. if (directive) {
  104. directive.el = node
  105. compiler.bindDirective(directive)
  106. }
  107. } else if (ctrlExp && !root) { // nested controllers
  108. new Compiler(node, {
  109. child: true,
  110. parentCompiler: compiler
  111. })
  112. } else { // normal node
  113. // parse if has attributes
  114. if (node.attributes && node.attributes.length) {
  115. var attrs = slice.call(node.attributes),
  116. i = attrs.length, attr, j, valid, exps, exp
  117. while (i--) {
  118. attr = attrs[i]
  119. if (attr.name === ctrlAttr) continue
  120. valid = false
  121. exps = attr.value.split(',')
  122. j = exps.length
  123. while (j--) {
  124. exp = exps[j]
  125. directive = DirectiveParser.parse(attr.name, exp)
  126. if (directive) {
  127. valid = true
  128. directive.el = node
  129. compiler.bindDirective(directive)
  130. }
  131. }
  132. if (valid) node.removeAttribute(attr.name)
  133. }
  134. }
  135. // recursively compile childNodes
  136. if (node.childNodes.length) {
  137. slice.call(node.childNodes).forEach(compiler.compileNode, compiler)
  138. }
  139. }
  140. }
  141. }
  142. /*
  143. * Compile a text node
  144. */
  145. CompilerProto.compileTextNode = function (node) {
  146. var tokens = TextParser.parse(node)
  147. if (!tokens) return
  148. var compiler = this,
  149. dirname = config.prefix + '-text',
  150. el, token, directive
  151. for (var i = 0, l = tokens.length; i < l; i++) {
  152. token = tokens[i]
  153. el = document.createTextNode('')
  154. if (token.key) {
  155. directive = DirectiveParser.parse(dirname, token.key)
  156. if (directive) {
  157. directive.el = el
  158. compiler.bindDirective(directive)
  159. }
  160. } else {
  161. el.nodeValue = token
  162. }
  163. node.parentNode.insertBefore(el, node)
  164. }
  165. node.parentNode.removeChild(node)
  166. }
  167. /*
  168. * Create binding and attach getter/setter for a key to the viewmodel object
  169. */
  170. CompilerProto.createBinding = function (key) {
  171. config.log(' created binding: ' + key)
  172. var binding = new Binding(this, key)
  173. this.bindings[key] = binding
  174. if (binding.isComputed) this.computed.push(binding)
  175. return binding
  176. }
  177. /*
  178. * Add a directive instance to the correct binding & viewmodel
  179. */
  180. CompilerProto.bindDirective = function (directive) {
  181. this.directives.push(directive)
  182. directive.compiler = this
  183. directive.vm = this.vm
  184. var key = directive.key,
  185. compiler = this
  186. // deal with each block
  187. if (this.each) {
  188. if (key.indexOf(this.eachPrefix) === 0) {
  189. key = directive.key = key.replace(this.eachPrefix, '')
  190. } else {
  191. compiler = this.parentCompiler
  192. }
  193. }
  194. // deal with nesting
  195. compiler = traceOwnerCompiler(directive, compiler)
  196. var binding = compiler.bindings[key] || compiler.createBinding(key)
  197. binding.instances.push(directive)
  198. directive.binding = binding
  199. // for newly inserted sub-VMs (each items), need to bind deps
  200. // because they didn't get processed when the parent compiler
  201. // was binding dependencies.
  202. var i, dep
  203. if (binding.contextDeps) {
  204. i = binding.contextDeps.length
  205. while (i--) {
  206. dep = this.bindings[binding.contextDeps[i]]
  207. dep.subs.push(directive)
  208. }
  209. }
  210. // invoke bind hook if exists
  211. if (directive.bind) {
  212. directive.bind(binding.value)
  213. }
  214. // set initial value
  215. directive.update(binding.value)
  216. if (binding.isComputed) {
  217. directive.refresh()
  218. }
  219. }
  220. /*
  221. * Process subscriptions for computed properties that has
  222. * dynamic context dependencies
  223. */
  224. CompilerProto.bindContexts = function (bindings) {
  225. var i = bindings.length, j, k, binding, depKey, dep, ins
  226. while (i--) {
  227. binding = bindings[i]
  228. j = binding.contextDeps.length
  229. while (j--) {
  230. depKey = binding.contextDeps[j]
  231. k = binding.instances.length
  232. while (k--) {
  233. ins = binding.instances[k]
  234. dep = ins.compiler.bindings[depKey]
  235. dep.subs.push(ins)
  236. }
  237. }
  238. }
  239. }
  240. /*
  241. * Unbind and remove element
  242. */
  243. CompilerProto.destroy = function () {
  244. var i, key, dir, listener, inss
  245. // remove all directives that are instances of external bindings
  246. i = this.directives.length
  247. while (i--) {
  248. dir = this.directives[i]
  249. if (dir.binding.compiler !== this) {
  250. inss = dir.binding.instances
  251. if (inss) inss.splice(inss.indexOf(dir), 1)
  252. }
  253. dir.unbind()
  254. }
  255. // remove all listeners on eventbus
  256. i = this.listeners.length
  257. while (i--) {
  258. listener = this.listeners[i]
  259. eventbus.off(listener.event, listener.handler)
  260. }
  261. // unbind all bindings
  262. for (key in this.bindings) {
  263. this.bindings[key].unbind()
  264. }
  265. // remove el
  266. this.el.compiler = null
  267. this.el.parentNode.removeChild(this.el)
  268. }
  269. // Helpers --------------------------------------------------------------------
  270. /*
  271. * determine which viewmodel a key belongs to based on nesting symbols
  272. */
  273. function traceOwnerCompiler (key, compiler) {
  274. if (key.nesting) {
  275. var levels = key.nesting
  276. while (compiler.parentCompiler && levels--) {
  277. compiler = compiler.parentCompiler
  278. }
  279. } else if (key.root) {
  280. while (compiler.parentCompiler) {
  281. compiler = compiler.parentCompiler
  282. }
  283. }
  284. return compiler
  285. }
  286. module.exports = Compiler