compiler.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750
  1. var Emitter = require('./emitter'),
  2. Observer = require('./observer'),
  3. config = require('./config'),
  4. utils = require('./utils'),
  5. Binding = require('./binding'),
  6. Directive = require('./directive'),
  7. TextParser = require('./text-parser'),
  8. DepsParser = require('./deps-parser'),
  9. ExpParser = require('./exp-parser'),
  10. // cache methods
  11. slice = Array.prototype.slice,
  12. log = utils.log,
  13. makeHash = utils.hash,
  14. extend = utils.extend,
  15. def = utils.defProtected,
  16. hasOwn = Object.prototype.hasOwnProperty,
  17. // hooks to register
  18. hooks = [
  19. 'created', 'ready',
  20. 'beforeDestroy', 'afterDestroy',
  21. 'attached', 'detached'
  22. ]
  23. /**
  24. * The DOM compiler
  25. * scans a DOM node and compile bindings for a ViewModel
  26. */
  27. function Compiler (vm, options) {
  28. var compiler = this
  29. // indicate that we are intiating this instance
  30. // so we should not run any transitions
  31. compiler.init = true
  32. // process and extend options
  33. options = compiler.options = options || makeHash()
  34. utils.processOptions(options)
  35. // copy data, methods & compiler options
  36. var data = compiler.data = options.data || {}
  37. extend(vm, data, true)
  38. extend(vm, options.methods, true)
  39. extend(compiler, options.compilerOptions)
  40. // initialize element
  41. var el = compiler.setupElement(options)
  42. log('\nnew VM instance:', el.tagName, '\n')
  43. // set compiler properties
  44. compiler.vm = vm
  45. compiler.bindings = makeHash()
  46. compiler.dirs = []
  47. compiler.deferred = []
  48. compiler.exps = []
  49. compiler.computed = []
  50. compiler.childCompilers = []
  51. compiler.emitter = new Emitter()
  52. // set inenumerable VM properties
  53. def(vm, '$', makeHash())
  54. def(vm, '$el', el)
  55. def(vm, '$compiler', compiler)
  56. def(vm, '$root', getRoot(compiler).vm)
  57. // set parent VM
  58. // and register child id on parent
  59. var parent = compiler.parentCompiler,
  60. childId = utils.attr(el, 'component-id')
  61. if (parent) {
  62. parent.childCompilers.push(compiler)
  63. def(vm, '$parent', parent.vm)
  64. if (childId) {
  65. compiler.childId = childId
  66. parent.vm.$[childId] = vm
  67. }
  68. }
  69. // setup observer
  70. compiler.setupObserver()
  71. // create bindings for computed properties
  72. var computed = options.computed
  73. if (computed) {
  74. for (var key in computed) {
  75. compiler.createBinding(key)
  76. }
  77. }
  78. // beforeCompile hook
  79. compiler.execHook('created')
  80. // the user might have set some props on the vm
  81. // so copy it back to the data...
  82. extend(data, vm)
  83. // observe the data
  84. compiler.observeData(data)
  85. // for repeated items, create an index binding
  86. // which should be inenumerable but configurable
  87. if (compiler.repeat) {
  88. //data.$index = compiler.repeatIndex
  89. def(data, '$index', compiler.repeatIndex, false, true)
  90. compiler.createBinding('$index')
  91. }
  92. // now parse the DOM, during which we will create necessary bindings
  93. // and bind the parsed directives
  94. compiler.compile(el, true)
  95. // bind deferred directives (child components)
  96. compiler.deferred.forEach(compiler.bindDirective, compiler)
  97. // extract dependencies for computed properties
  98. compiler.parseDeps()
  99. // done!
  100. compiler.init = false
  101. // post compile / ready hook
  102. compiler.execHook('ready')
  103. }
  104. var CompilerProto = Compiler.prototype
  105. /**
  106. * Initialize the VM/Compiler's element.
  107. * Fill it in with the template if necessary.
  108. */
  109. CompilerProto.setupElement = function (options) {
  110. // create the node first
  111. var el = this.el = typeof options.el === 'string'
  112. ? document.querySelector(options.el)
  113. : options.el || document.createElement(options.tagName || 'div')
  114. var template = options.template
  115. if (template) {
  116. // replace option: use the first node in
  117. // the template directly
  118. if (options.replace && template.childNodes.length === 1) {
  119. var replacer = template.childNodes[0].cloneNode(true)
  120. if (el.parentNode) {
  121. el.parentNode.insertBefore(replacer, el)
  122. el.parentNode.removeChild(el)
  123. }
  124. el = replacer
  125. } else {
  126. el.innerHTML = ''
  127. el.appendChild(template.cloneNode(true))
  128. }
  129. }
  130. // apply element options
  131. if (options.id) el.id = options.id
  132. if (options.className) el.className = options.className
  133. var attrs = options.attributes
  134. if (attrs) {
  135. for (var attr in attrs) {
  136. el.setAttribute(attr, attrs[attr])
  137. }
  138. }
  139. return el
  140. }
  141. /**
  142. * Setup observer.
  143. * The observer listens for get/set/mutate events on all VM
  144. * values/objects and trigger corresponding binding updates.
  145. * It also listens for lifecycle hooks.
  146. */
  147. CompilerProto.setupObserver = function () {
  148. var compiler = this,
  149. bindings = compiler.bindings,
  150. options = compiler.options,
  151. observer = compiler.observer = new Emitter()
  152. // a hash to hold event proxies for each root level key
  153. // so they can be referenced and removed later
  154. observer.proxies = makeHash()
  155. // add own listeners which trigger binding updates
  156. observer
  157. .on('get', function (key) {
  158. check(key)
  159. DepsParser.catcher.emit('get', bindings[key])
  160. })
  161. .on('set', function (key, val) {
  162. observer.emit('change:' + key, val)
  163. check(key)
  164. bindings[key].update(val)
  165. })
  166. .on('mutate', function (key, val, mutation) {
  167. observer.emit('change:' + key, val, mutation)
  168. check(key)
  169. bindings[key].pub()
  170. })
  171. // register hooks
  172. hooks.forEach(function (hook) {
  173. var fns = options[hook]
  174. if (Array.isArray(fns)) {
  175. var i = fns.length
  176. // since hooks were merged with child at head,
  177. // we loop reversely.
  178. while (i--) {
  179. register(hook, fns[i])
  180. }
  181. } else if (fns) {
  182. register(hook, fns)
  183. }
  184. })
  185. function register (hook, fn) {
  186. observer.on('hook:' + hook, function () {
  187. fn.call(compiler.vm, options)
  188. })
  189. }
  190. function check (key) {
  191. if (!bindings[key]) {
  192. compiler.createBinding(key)
  193. }
  194. }
  195. }
  196. CompilerProto.observeData = function (data) {
  197. var compiler = this,
  198. observer = compiler.observer
  199. // recursively observe nested properties
  200. Observer.observe(data, '', observer)
  201. // also create binding for top level $data
  202. // so it can be used in templates too
  203. var $dataBinding = compiler.bindings['$data'] = new Binding(compiler, '$data')
  204. $dataBinding.update(data)
  205. // allow $data to be swapped
  206. Object.defineProperty(compiler.vm, '$data', {
  207. enumerable: false,
  208. get: function () {
  209. compiler.observer.emit('get', '$data')
  210. return compiler.data
  211. },
  212. set: function (newData) {
  213. var oldData = compiler.data
  214. Observer.unobserve(oldData, '', observer)
  215. compiler.data = newData
  216. Observer.copyPaths(newData, oldData)
  217. Observer.observe(newData, '', observer)
  218. compiler.observer.emit('set', '$data', newData)
  219. }
  220. })
  221. // emit $data change on all changes
  222. observer.on('set', function (key) {
  223. if (key !== '$data') {
  224. $dataBinding.update(compiler.data)
  225. }
  226. })
  227. }
  228. /**
  229. * Compile a DOM node (recursive)
  230. */
  231. CompilerProto.compile = function (node, root) {
  232. var compiler = this,
  233. nodeType = node.nodeType,
  234. tagName = node.tagName
  235. if (nodeType === 1 && tagName !== 'SCRIPT') { // a normal node
  236. // skip anything with v-pre
  237. if (utils.attr(node, 'pre') !== null) return
  238. // special attributes to check
  239. var repeatExp,
  240. withKey,
  241. partialId,
  242. directive,
  243. componentId = utils.attr(node, 'component') || tagName.toLowerCase(),
  244. componentCtor = compiler.getOption('components', componentId)
  245. // It is important that we access these attributes
  246. // procedurally because the order matters.
  247. //
  248. // `utils.attr` removes the attribute once it gets the
  249. // value, so we should not access them all at once.
  250. // v-repeat has the highest priority
  251. // and we need to preserve all other attributes for it.
  252. /* jshint boss: true */
  253. if (repeatExp = utils.attr(node, 'repeat')) {
  254. // repeat block cannot have v-id at the same time.
  255. directive = Directive.parse('repeat', repeatExp, compiler, node)
  256. if (directive) {
  257. directive.Ctor = componentCtor
  258. // defer child component compilation
  259. // so by the time they are compiled, the parent
  260. // would have collected all bindings
  261. compiler.deferred.push(directive)
  262. }
  263. // v-with has 2nd highest priority
  264. } else if (root !== true && ((withKey = utils.attr(node, 'with')) || componentCtor)) {
  265. directive = Directive.parse('with', withKey || '', compiler, node)
  266. if (directive) {
  267. directive.Ctor = componentCtor
  268. compiler.deferred.push(directive)
  269. }
  270. } else {
  271. // check transition property
  272. node.vue_trans = utils.attr(node, 'transition')
  273. // replace innerHTML with partial
  274. partialId = utils.attr(node, 'partial')
  275. if (partialId) {
  276. var partial = compiler.getOption('partials', partialId)
  277. if (partial) {
  278. node.innerHTML = ''
  279. node.appendChild(partial.cloneNode(true))
  280. }
  281. }
  282. // finally, only normal directives left!
  283. compiler.compileNode(node)
  284. }
  285. } else if (nodeType === 3) { // text node
  286. compiler.compileTextNode(node)
  287. }
  288. }
  289. /**
  290. * Compile a normal node
  291. */
  292. CompilerProto.compileNode = function (node) {
  293. var i, j,
  294. attrs = slice.call(node.attributes),
  295. prefix = config.prefix + '-'
  296. // parse if has attributes
  297. if (attrs && attrs.length) {
  298. var attr, isDirective, exps, exp, directive, dirname
  299. // loop through all attributes
  300. i = attrs.length
  301. while (i--) {
  302. attr = attrs[i]
  303. isDirective = false
  304. if (attr.name.indexOf(prefix) === 0) {
  305. // a directive - split, parse and bind it.
  306. isDirective = true
  307. exps = Directive.split(attr.value)
  308. // loop through clauses (separated by ",")
  309. // inside each attribute
  310. j = exps.length
  311. while (j--) {
  312. exp = exps[j]
  313. dirname = attr.name.slice(prefix.length)
  314. directive = Directive.parse(dirname, exp, this, node)
  315. if (directive) {
  316. this.bindDirective(directive)
  317. }
  318. }
  319. } else {
  320. // non directive attribute, check interpolation tags
  321. exp = TextParser.parseAttr(attr.value)
  322. if (exp) {
  323. directive = Directive.parse('attr', attr.name + ':' + exp, this, node)
  324. if (directive) {
  325. this.bindDirective(directive)
  326. }
  327. }
  328. }
  329. if (isDirective && dirname !== 'cloak') {
  330. node.removeAttribute(attr.name)
  331. }
  332. }
  333. }
  334. // recursively compile childNodes
  335. if (node.childNodes.length) {
  336. slice.call(node.childNodes).forEach(this.compile, this)
  337. }
  338. }
  339. /**
  340. * Compile a text node
  341. */
  342. CompilerProto.compileTextNode = function (node) {
  343. var tokens = TextParser.parse(node.nodeValue)
  344. if (!tokens) return
  345. var el, token, directive, partial, partialId, partialNodes
  346. for (var i = 0, l = tokens.length; i < l; i++) {
  347. token = tokens[i]
  348. directive = partialNodes = null
  349. if (token.key) { // a binding
  350. if (token.key.charAt(0) === '>') { // a partial
  351. partialId = token.key.slice(1).trim()
  352. partial = this.getOption('partials', partialId)
  353. if (partial) {
  354. el = partial.cloneNode(true)
  355. // save an Array reference of the partial's nodes
  356. // so we can compile them AFTER appending the fragment
  357. partialNodes = slice.call(el.childNodes)
  358. }
  359. } else { // a real binding
  360. if (!token.html) { // text binding
  361. el = document.createTextNode('')
  362. directive = Directive.parse('text', token.key, this, el)
  363. } else { // html binding
  364. el = document.createComment(config.prefix + '-html')
  365. directive = Directive.parse('html', token.key, this, el)
  366. }
  367. }
  368. } else { // a plain string
  369. el = document.createTextNode(token)
  370. }
  371. // insert node
  372. node.parentNode.insertBefore(el, node)
  373. // bind directive
  374. if (directive) {
  375. this.bindDirective(directive)
  376. }
  377. // compile partial after appending, because its children's parentNode
  378. // will change from the fragment to the correct parentNode.
  379. // This could affect directives that need access to its element's parentNode.
  380. if (partialNodes) {
  381. partialNodes.forEach(this.compile, this)
  382. }
  383. }
  384. node.parentNode.removeChild(node)
  385. }
  386. /**
  387. * Add a directive instance to the correct binding & viewmodel
  388. */
  389. CompilerProto.bindDirective = function (directive) {
  390. // keep track of it so we can unbind() later
  391. this.dirs.push(directive)
  392. // for empty or literal directives, simply call its bind()
  393. // and we're done.
  394. if (directive.isEmpty || !directive._update) {
  395. if (directive.bind) directive.bind()
  396. return
  397. }
  398. // otherwise, we got more work to do...
  399. var binding,
  400. compiler = this,
  401. key = directive.key
  402. if (directive.isExp) {
  403. // expression bindings are always created on current compiler
  404. binding = compiler.createBinding(key, true, directive.isFn)
  405. } else {
  406. // recursively locate which compiler owns the binding
  407. while (compiler) {
  408. if (compiler.hasKey(key)) {
  409. break
  410. } else {
  411. compiler = compiler.parentCompiler
  412. }
  413. }
  414. compiler = compiler || this
  415. binding = compiler.bindings[key] || compiler.createBinding(key)
  416. }
  417. binding.instances.push(directive)
  418. directive.binding = binding
  419. // invoke bind hook if exists
  420. if (directive.bind) {
  421. directive.bind()
  422. }
  423. // set initial value
  424. directive.update(binding.val(), true)
  425. }
  426. /**
  427. * Create binding and attach getter/setter for a key to the viewmodel object
  428. */
  429. CompilerProto.createBinding = function (key, isExp, isFn) {
  430. log(' created binding: ' + key)
  431. var compiler = this,
  432. bindings = compiler.bindings,
  433. computed = compiler.options.computed,
  434. binding = new Binding(compiler, key, isExp, isFn)
  435. if (isExp) {
  436. // expression bindings are anonymous
  437. compiler.defineExp(key, binding)
  438. } else {
  439. bindings[key] = binding
  440. if (binding.root) {
  441. // this is a root level binding. we need to define getter/setters for it.
  442. if (computed && computed[key]) {
  443. // computed property
  444. compiler.defineComputed(key, binding, computed[key])
  445. } else {
  446. // normal property
  447. compiler.defineProp(key, binding)
  448. }
  449. } else {
  450. // ensure path in data so it can be observed
  451. Observer.ensurePath(compiler.data, key)
  452. var parentKey = key.slice(0, key.lastIndexOf('.'))
  453. if (!bindings[parentKey]) {
  454. // this is a nested value binding, but the binding for its parent
  455. // has not been created yet. We better create that one too.
  456. compiler.createBinding(parentKey)
  457. }
  458. }
  459. }
  460. return binding
  461. }
  462. /**
  463. * Define the getter/setter for a root-level property on the VM
  464. * and observe the initial value
  465. */
  466. CompilerProto.defineProp = function (key, binding) {
  467. var compiler = this,
  468. data = compiler.data,
  469. ob = data.__observer__
  470. // make sure the key is present in data
  471. // so it can be observed
  472. if (!(key in data)) {
  473. data[key] = undefined
  474. }
  475. // if the data object is already observed, but the key
  476. // is not observed, we need to add it to the observed keys.
  477. if (ob && !(key in ob.values)) {
  478. Observer.convert(data, key)
  479. }
  480. binding.value = data[key]
  481. Object.defineProperty(compiler.vm, key, {
  482. get: function () {
  483. return compiler.data[key]
  484. },
  485. set: function (val) {
  486. compiler.data[key] = val
  487. }
  488. })
  489. }
  490. /**
  491. * Define an expression binding, which is essentially
  492. * an anonymous computed property
  493. */
  494. CompilerProto.defineExp = function (key, binding) {
  495. var getter = ExpParser.parse(key, this)
  496. if (getter) {
  497. this.markComputed(binding, getter)
  498. this.exps.push(binding)
  499. }
  500. }
  501. /**
  502. * Define a computed property on the VM
  503. */
  504. CompilerProto.defineComputed = function (key, binding, value) {
  505. this.markComputed(binding, value)
  506. Object.defineProperty(this.vm, key, {
  507. get: binding.value.$get,
  508. set: binding.value.$set
  509. })
  510. }
  511. /**
  512. * Process a computed property binding
  513. * so its getter/setter are bound to proper context
  514. */
  515. CompilerProto.markComputed = function (binding, value) {
  516. binding.isComputed = true
  517. // bind the accessors to the vm
  518. if (binding.isFn) {
  519. binding.value = value
  520. } else {
  521. if (typeof value === 'function') {
  522. value = { $get: value }
  523. }
  524. binding.value = {
  525. $get: utils.bind(value.$get, this.vm),
  526. $set: value.$set
  527. ? utils.bind(value.$set, this.vm)
  528. : undefined
  529. }
  530. }
  531. // keep track for dep parsing later
  532. this.computed.push(binding)
  533. }
  534. /**
  535. * Retrive an option from the compiler
  536. */
  537. CompilerProto.getOption = function (type, id) {
  538. var opts = this.options,
  539. parent = this.parentCompiler
  540. return (opts[type] && opts[type][id]) || (
  541. parent
  542. ? parent.getOption(type, id)
  543. : utils[type] && utils[type][id]
  544. )
  545. }
  546. /**
  547. * Emit lifecycle events to trigger hooks
  548. */
  549. CompilerProto.execHook = function (event) {
  550. event = 'hook:' + event
  551. this.observer.emit(event)
  552. this.emitter.emit(event)
  553. }
  554. /**
  555. * Check if a compiler's data contains a keypath
  556. */
  557. CompilerProto.hasKey = function (key) {
  558. var baseKey = key.split('.')[0]
  559. return hasOwn.call(this.data, baseKey) ||
  560. hasOwn.call(this.vm, baseKey)
  561. }
  562. /**
  563. * Collect dependencies for computed properties
  564. */
  565. CompilerProto.parseDeps = function () {
  566. if (!this.computed.length) return
  567. DepsParser.parse(this.computed)
  568. }
  569. /**
  570. * Unbind and remove element
  571. */
  572. CompilerProto.destroy = function () {
  573. // avoid being called more than once
  574. // this is irreversible!
  575. if (this.destroyed) return
  576. var compiler = this,
  577. i, key, dir, instances, binding,
  578. vm = compiler.vm,
  579. el = compiler.el,
  580. directives = compiler.dirs,
  581. exps = compiler.exps,
  582. bindings = compiler.bindings
  583. compiler.execHook('beforeDestroy')
  584. // unobserve data
  585. Observer.unobserve(compiler.data, '', compiler.observer)
  586. // unbind all direcitves
  587. i = directives.length
  588. while (i--) {
  589. dir = directives[i]
  590. // if this directive is an instance of an external binding
  591. // e.g. a directive that refers to a variable on the parent VM
  592. // we need to remove it from that binding's instances
  593. // * empty and literal bindings do not have binding.
  594. if (dir.binding && dir.binding.compiler !== compiler) {
  595. instances = dir.binding.instances
  596. if (instances) instances.splice(instances.indexOf(dir), 1)
  597. }
  598. dir.unbind()
  599. }
  600. // unbind all expressions (anonymous bindings)
  601. i = exps.length
  602. while (i--) {
  603. exps[i].unbind()
  604. }
  605. // unbind all own bindings
  606. for (key in bindings) {
  607. binding = bindings[key]
  608. if (binding) {
  609. binding.unbind()
  610. }
  611. }
  612. // remove self from parentCompiler
  613. var parent = compiler.parentCompiler,
  614. childId = compiler.childId
  615. if (parent) {
  616. parent.childCompilers.splice(parent.childCompilers.indexOf(compiler), 1)
  617. if (childId) {
  618. delete parent.vm.$[childId]
  619. }
  620. }
  621. // finally remove dom element
  622. if (el === document.body) {
  623. el.innerHTML = ''
  624. } else {
  625. vm.$remove()
  626. }
  627. this.destroyed = true
  628. // emit destroy hook
  629. compiler.execHook('afterDestroy')
  630. // finally, unregister all listeners
  631. compiler.observer.off()
  632. compiler.emitter.off()
  633. }
  634. // Helpers --------------------------------------------------------------------
  635. /**
  636. * shorthand for getting root compiler
  637. */
  638. function getRoot (compiler) {
  639. while (compiler.parentCompiler) {
  640. compiler = compiler.parentCompiler
  641. }
  642. return compiler
  643. }
  644. module.exports = Compiler