[英]How to check if a request has post data in a Total.js controller
I want a solution to keep view and post actions on the same function, by verifying if the user submited some data. 我想要一种解决方案,通过验证用户是否提交了一些数据来保持对同一功能的查看和发布操作。
My total.js controller is like this 我的total.js控制器就是这样
# framework
exports.install = (framework) ->
framework.route "/subscribe", subscribe
framework.route "/subscribe", subscribe, ['post']
# subscribe form and action
subscribe = ->
self = this
post = self.post
if post
Subscriber = self.model('subscriber')
Subscriber.save post
self.view "form"
The problem is that post
is {}
when I'm just viewing the page (not submiting data), so it always enter on if
. 问题是当我仅查看页面(不提交数据)时,
post
是{}
,因此它总是在if
输入。
If I compare to {}
( if post isnt {}
) the condition is always false, probably because self.post
is not an empty object. 如果我与
{}
( if post isnt {}
)进行比较, if post isnt {}
该条件始终为false,可能是因为self.post
不是一个空对象。
[update] [更新]
When viewing the page: 查看页面时:
console.log post #logs {}
When submiting the form: 提交表格时:
console.log post #logs { type: 1, email: "email@example.com" }
You don't clearly understand is
/ isnt
. 您不清楚
is
/ isnt
。 Look at that example: 看那个例子:
coffee> {} is {}
false
Surprising ? 令人惊讶吗? Not if you know the
is
test is two variable references the same object. 如果您知道
is
测试不是两个变量引用同一对象, is
不是这样。 Not identical . 不一样 。 Really the same object:
确实是同一对象:
coffee> obj1 = {}
{}
coffee> obj2 = obj1
{}
coffee> obj1 is obj2
true
You might then go to ==
in order to test for equivalence . 然后,您可以转到
==
以测试等效性 。 But: 但:
coffee> {} == {}
false
Unfortunately, JavaScript does not provide a easy way to test for object equality . 不幸的是, JavaScript没有提供一种简单的方法来测试对象是否相等 。
In you case, you should resort on some trick. 在这种情况下,您应该采取一些技巧。 Like:
喜欢:
if (i for i in post).length == 0
...
Or maybe check for the presence of some key field: 或者,也许检查某些关键字段的存在:
if 'type' not of post
...
Simple checking: 简单检查:
function some_action_in_controller() {
var self = this;
// self.body is same as self.post
var isEmpty = Object.keys(self.body).length === 0);
self.json({ result: isEmpty });
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.