The first thing is to receive the recipe id from the route and feed it into the recipe edit part. The route looks like this:
FlowRouter.route('/recipes/:recipeId/edit', { name: 'recipes.edit', action() { BlazeLayout.render('mainLayout', { content: 'recipeEditPage' }); } });
The mark up of the page that hosts the part:
<div class="col-md-8"> {{>recipeEditPart recipeId=recipeId}} </div>
And the code behind, note the use of FlowRouter to get the parameters from the url:
Template.recipeEditPage.helpers({ recipeId() { return FlowRouter.getParam('recipeId'); } });
Next, the part will use this identifier to request the recipe from a server publication. Notice that the subscribe method accepts a callback that is invoked when meteor finishes populating the local collection with data from the server. At that moment, we can query the local 'Recipes' collection to see if this is an existing recipe and set the observable properties into knockout's view model if it is.
Template.recipeEditPart.onCreated(function() { var recipeId = this.data.recipeId; var viewModel = this.viewModel = new RecipeViewModel(); viewModel._id = recipeId; Meteor.subscribe('recipe', recipeId, function() { var recipe = Recipes.findOne(recipeId); if (recipe) { viewModel.name(recipe.name); } }); });
Lastly, when the document is submitted to the server use mongo's 'upsert' to either insert or update the document:
export const addOrUpdate = new ValidatedMethod({ name: 'recipe.addOrUpdate', validate: new SimpleSchema({ recipe: { type: RecipeSchema } }).validator({ clean: true }), mixins: [Mixins.authenticated], run({ recipe }) { Recipes.update({ _id: recipe._id }, recipe, { upsert: true }); } });
Visit the live demo or view the soure code.
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.