1

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

# 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.

If I compare to {} (if post isnt {}) the condition is always false, probably because self.post is not an empty object.

[update]

  • When viewing the page:

    console.log post    #logs {}
    
  • When submiting the form:

    console.log post    #logs { type: 1, email: "email@example.com" }
    
menjaraz
  • 7,551
  • 4
  • 41
  • 81
paulodiovani
  • 1,208
  • 2
  • 16
  • 34

2 Answers2

3

You don't clearly understand is/isnt. Look at that example:

coffee> {} is {}
false

Surprising ? Not if you know the is test is two variable references the same object. 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.

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
  ...
Community
  • 1
  • 1
Sylvain Leroux
  • 50,096
  • 7
  • 103
  • 125
2

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 }); 
}
Peter Sirka
  • 748
  • 5
  • 10