Skip to content

Instantly share code, notes, and snippets.

@mrosenberg
Created February 18, 2015 01:57
Show Gist options
  • Save mrosenberg/b95c14c9980d09f4fb43 to your computer and use it in GitHub Desktop.
Save mrosenberg/b95c14c9980d09f4fb43 to your computer and use it in GitHub Desktop.
WordPress tag like component for EmberJS
<label class="control-label" {{bind-attr for="inputField.elementId"}}>
{{label}}
</label>
<div class="input-group">
<span {{action 'add'}} class="input-group-addon">
<span class="glyphicon glyphicon-plus-sign"></span>
</span>
{{input
action="add"
on="enter"
class="form-control"
placeholder="Separate Tags With Commas"
name=label
value=newTags
}}
</div>
<ul class="list-group">
{{#each tag in tagList}}
<li class="list-group-item"><span {{action 'remove' tag}} class="tag glyphicon glyphicon-remove-sign"></span> {{tag.name}}</li>
{{/each}}
</ul>
export default Ember.Component.extend({
classNames: ['tag-list', 'form-group'],
actions: {
add: function() {
var tags
tags = this.get('tags');
this.get('newTags')
.split(',')
.map(this._cleanTags)
.map(this._createTag, this)
.forEach(function(tag) {
tags.pushObject(tag);
});
this.sendAction('add', tags);
this.set('newTags', null);
},
remove: function(tag) {
this.sendAction('remove', tag);
this.get('tags').removeObject(tag);
}
},
tags: [],
tagIDPath: 'content',
tagNamePath: 'content',
tagList: function() {
return this.get('tags');
}.property('tags'),
_uuid: function() {
// Thanks Boofa http://stackoverflow.com/posts/2117523/revisions
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
},
_cleanTags: function(tag) {
return tag.replace(/\s*,\s*/g, ',')
.replace(/,+/g, ',')
.replace(/[,\s]+$/, '')
.replace(/^[,\s]+/, '');
},
_createTag: function(tag) {
return Ember.Object.create({
id: this._uuid(),
name: tag
});
},
_makeTag: function(tag) {
var id, name;
id = this.get('tagIDPath').replace(/^content\.?/, '');
name = this.get('tagNamePath').replace(/^content\.?/, '');
return Ember.Object.create({
id: tag.get(id),
name: tag.get(name)
});
},
_init: function() {
this.set('tags', this.get('content').map(this._makeTag, this));
}.on('init')
});
{{input-tags
add="addTag"
remove="removeTag"
label='Include'
tagIDPath='content.id'
tagNamePath='content.value'
content=campaignIncludes
}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment