I have two models with a many to many relationship to each other - the first is 'recipe', the second is 'tag':
App.Recipe = DS.Model.extend({
title: attr('string'),
source: attr('string'),
notes: attr('string'),
isFavourite: attr('boolean', {defaultValue: false}),
tags: hasMany('tag', { async: true })
});
App.Tag = DS.Model.extend({
name: attr('string'),
recipes: hasMany('recipe', { async: true })
});
In my template, I have an input for adding a tag to a recipe. User can add either one tag, or multiple by separating each tag with a comma.
{{input type="text" enter="AddTags" placeholder="add a tag (or two!)"}}
This calls 'AddTags' within my RecipeController:
App.RecipeController = Ember.ObjectController.extend({
actions: {
AddTags: function(tags){
var store = this.store;
var thisRecipe = this.get('model');
var thisRecipeTags = thisRecipe.get('tags');
var addedTags = tags.split(',');
for (i = 0; i < addedTags.length; i++) {
tag = store.createRecord('tag', {
name: addedTags[i]
});
thisRecipeTags.addObject(tag);
}
}
}
});
This works wonderfully - however - I would like to refactor the function so that a new tag is only created if one with the same name doesn't already exist:
AddTags: function(tags){
var store = this.store;
var thisRecipe = this.get('model');
var thisRecipeTags = thisRecipe.get('tags');
var addedTags = tags.split(',');
for (i = 0; i < addedTags.length; i++) {
// If exisiting tag where name == addedTags[i]
tag = existing tag object here
// Else create a new tag
tag = store.createRecord('tag', {
name: addedTags[i]
});
thisRecipeTags.addObject(tag);
}
}
How can I do this?
Update: I have set up a JS bin with the relevant code here: http://ift.tt/17IogiL
Aucun commentaire:
Enregistrer un commentaire