Skip to content

Commit

Permalink
Merge pull request #20 from Fishfaceeast/fix
Browse files Browse the repository at this point in the history
Fix `.add()` 无法覆盖同名模板的问题,并增加相应单元测试
  • Loading branch information
cssmagic committed Nov 2, 2015
2 parents 0bdfc34 + af02b60 commit f711a3e
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 4 deletions.
5 changes: 4 additions & 1 deletion src/underscore-template.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,10 +98,13 @@ var template = function () {
if (templateCode) {
var templateId = _toTemplateId(id)
/** DEBUG_INFO_START **/
if (_cacheTemplate[templateId]) {
if (_cacheTemplate[templateId] || _cacheCompiledTemplate[templateId]) {
console.warn('[Template] Template id "' + templateId + '" already existed.')
}
/** DEBUG_INFO_END **/
if (_cacheCompiledTemplate[templateId]) {
_cacheCompiledTemplate[templateId] = null
}
result = _cacheTemplate[templateId] = templateCode
} else {
//todo: support `_.template.add(id)` to add from dummy script element
Expand Down
23 changes: 20 additions & 3 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ void function () {
'</ul>'
].join('\n')

//compiledTemplate
var fn1 = _.template(templateCode1)
var fn2 = _.template(templateCode2)

//template data
var templateData1 = {text: HELLO}
var templateData2 = [
Expand Down Expand Up @@ -328,18 +332,31 @@ void function () {
expect(_cacheTemplate).to.deep.equal(data)
expect(_cacheCompiledTemplate).to.deep.equal({})
})
it('overwrites while adding existed template id', function () {
it('overwrites template while adding existed template id', function () {
expect(_cacheTemplate).to.deep.equal({})
data = {}

template.add(TEMPLATE_ID_1, templateCode1)
data[TEMPLATE_ID_1] = templateCode1
expect(_cacheTemplate).to.deep.equal(data)

template.add(TEMPLATE_ID_2, templateCode2)
data[TEMPLATE_ID_2] = templateCode2
template.add(TEMPLATE_ID_1, templateCode2)
data[TEMPLATE_ID_1] = templateCode2
expect(_cacheTemplate).to.deep.equal(data)
})
it('overwrites compiledTemplate while adding existed template id', function () {
expect(_cacheCompiledTemplate).to.deep.equal({})

template.add(TEMPLATE_ID_1, templateCode1)
template.render(TEMPLATE_ID_1, templateData1)
expect(_cacheCompiledTemplate[TEMPLATE_ID_1].source).to.equal(fn1.source)

template.add(TEMPLATE_ID_1, templateCode2)
expect(_cacheCompiledTemplate[TEMPLATE_ID_1]).to.equal(null)
template.render(TEMPLATE_ID_1, templateData2)
expect(_cacheCompiledTemplate[TEMPLATE_ID_1]).to.be.a('function')
expect(_cacheCompiledTemplate[TEMPLATE_ID_1].source).to.equal(fn2.source)
})
it('does nothing if missing template code as second param', function () {
expect(_cacheTemplate).to.deep.equal({})
template.add('foo')
Expand Down

0 comments on commit f711a3e

Please sign in to comment.