compiler.js 19 KB

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