Skip to content

Commit

Permalink
DOM convenience methods
Browse files Browse the repository at this point in the history
  • Loading branch information
yyx990803 committed Dec 18, 2013
1 parent 628c42c commit d132fdc
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 13 deletions.
7 changes: 2 additions & 5 deletions src/compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ var Emitter = require('./emitter'),
TextParser = require('./text-parser'),
DepsParser = require('./deps-parser'),
ExpParser = require('./exp-parser'),
transition = require('./transition'),
// cache deps ob
depsOb = DepsParser.observer,
// cache methods
Expand Down Expand Up @@ -618,10 +617,8 @@ CompilerProto.destroy = function () {
// finally remove dom element
if (el === document.body) {
el.innerHTML = ''
} else if (el.parentNode) {
transition(el, -1, function () {
el.parentNode.removeChild(el)
}, this)
} else {
vm.$remove()
}

// post teardown hook
Expand Down
55 changes: 53 additions & 2 deletions src/viewmodel.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
var Compiler = require('./compiler'),
def = require('./utils').defProtected
var Compiler = require('./compiler'),
def = require('./utils').defProtected,
transition = require('./transition')

/**
* ViewModel exposed to the user that holds data,
Expand Down Expand Up @@ -94,6 +95,56 @@ def(VMProto, '$emit', function () {
})
})

// DOM convenience methods

def(VMProto, '$appendTo', function (target) {
target = query(target)
var el = this.$el
transition(el, 1, function () {
target.appendChild(el)
}, this.$compiler)
})

def(VMProto, '$remove', function () {
var el = this.$el,
parent = el.parentNode
if (!parent) return
transition(el, -1, function () {
parent.removeChild(el)
}, this.$compiler)
})

def(VMProto, '$before', function (target) {
target = query(target)
var el = this.$el,
parent = target.parentNode
if (!parent) return
transition(el, 1, function () {
parent.insertBefore(el, target)
}, this.$compiler)
})

def(VMProto, '$after', function (target) {
target = query(target)
var el = this.$el,
parent = target.parentNode,
next = target.nextSibling
if (!parent) return
transition(el, 1, function () {
if (next) {
parent.insertBefore(el, next)
} else {
parent.appendChild(el)
}
}, this.$compiler)
})

function query (el) {
return typeof el === 'string'
? document.querySelector(el)
: el
}

/**
* If a VM doesn't contain a path, go up the prototype chain
* to locate the ancestor that has it.
Expand Down
9 changes: 3 additions & 6 deletions test/unit/specs/viewmodel.js
Original file line number Diff line number Diff line change
Expand Up @@ -302,12 +302,9 @@ describe('UNIT: ViewModel', function () {
}
}
},
el: {
getAttribute: function () {},
parentNode: {
removeChild: function () {
elRemoved = true
}
vm: {
$remove: function () {
elRemoved = true
}
}
}
Expand Down

0 comments on commit d132fdc

Please sign in to comment.