当我添加/编辑blogPost时,我的所有属性都是我的对象。我的代码:
添加帖子:
Template.postListAdmin.events({
'submit form': (e) => {
// Prevent default browser form submit
e.preventDefault();
let image = $('#js-image-uploaded'),
draft = $('[name="draft"]'),
isSmall = false,
isDrafted = false;
// If post draft, return true
if (draft.is(':checked')) isDrafted = true;
// If post image is small
// return true for add 'small' classe
if (image.height() < 80) isSmall = true;
let post = {
title: $('[name="title"]').val(),
image: image.attr('src'),
isSmall: isSmall,
description: $('[name="description"]').val(),
category: $('[name="category"]').val(),
time: $('[name="time"]').val(),
dateCreated: dateFormat($('[name="dateCreated"]').val(), 'yyyy-mm-dd'),
content: $('[name="content"]').val(),
draft: isDrafted
};
Meteor.call('posts.insert', post);
setTimeout(() => {
$('#js-post-form')
.toggleClass('is-hidden')
.find('input, textarea').val('');
}, 500);
}
});
编辑帖子:
Template.postEdit.events({
'submit form': function (e) {
e.preventDefault();
let image = $('#js-image-uploaded'),
draft = $('[name="draft"]'),
isSmall = false,
isDrafted;
if (draft.is(':checked')) isDrafted = true;
else isDrafted = false;
if (image.height() < 80) isSmall = true;
let post = {
slug: $('[name="title"]').val(),
title: $('[name="title"]').val(),
image: image.attr('src'),
isSmall: isSmall,
description: $('[name="description"]').val(),
category: $('[name="category"]').val(),
time: $('[name="time"]').val(),
dateCreated: dateFormat($('[name="dateCreated"]').val(), 'yyyy-mm-dd'),
dateModified: new Date(),
content: $('[name="content"]').val(),
draft: isDrafted
};
Meteor.call('posts.edit', this._id, post);
Router.go('postListAdmin');
},
});
我想优化我的代码并避免创建我的对象&#39; post&#39; 2次。
你知道我怎么能更好地理解这个?
谢谢你们每个人:)
答案 0 :(得分:0)
您可以通过定义不带let
关键字的帖子来实现您想要的目标。
例如:
post = {
title: $('[name="title"]').val(),
image: image.attr('src'),
isSmall: isSmall,
description: $('[name="description"]').val(),
category: $('[name="category"]').val(),
time: $('[name="time"]').val(),
dateCreated: dateFormat($('[name="dateCreated"]').val(), 'yyyy-mm-dd'),
content: $('[name="content"]').val(),
draft: isDrafted
};
但是,您必须决定如何处理这两个实例,因为它们并不完全相同。此外,将变量定义移到任一文件之外可能有助于组织代码。您可以使用名为utils
的客户端上的目录,并添加包含全局变量定义的文件。