-1
 obj1.listen(obj2, 'save', function(t) {
   t.preventDefault()
 })
 obj2 = {
   save: function save(a) {

     var saveOrNot = !1;
     this.trigger("save", {
       preventDefault: function() {
         saveOrNot = !0
       }
     });

     console.log("prevent default after")
     if (!saveOrNot) {
       console.log("got excuted")
     }

   }
 }

In my opinion, the line after the trigger line always gets executed because the preventDefault() doesn't get executed immediately. But the "got executed" message does not print. Does the code hang when triggering an event?

T J
  • 42,762
  • 13
  • 83
  • 138
  • Why do you use `!1` instead of false..?! – T J Jan 26 '16 at 17:57
  • You say this gets printed, that doesn't etc. The code you shared has syntax errors and isn't runnable. What is `listen`..? What type of backbone objects are these..? Please read [ask] and [mcve] – T J Jan 26 '16 at 18:04

1 Answers1

0

It's not executed because each time when you run the preventDefault function you set the saveOrNot value to true, but when you check for this value condition it's always false, hence the console log is never executed.

if (!saveOrNot) { // this is the line in scope => this is always false
    console.log("got excuted")
}

If you want to change the value condition to it's opposite state it's better to use negation:

saveOrNot = !saveOrNot;

I would rewrite your code in the below manner:

obj1.listen(obj2, 'save', function(t) {
   t.preventDefault()
 })
 obj2 = {
   save: function save(a) {

     var saveOrNot = 0;
     this.trigger("save", {
       preventDefault: function() {
         saveOrNot = !saveOrNot;
       }
     });

     console.log("prevent default after")
     if (!saveOrNot) {
       console.log("got excuted")
     }

   }
 }
Endre Simo
  • 11,330
  • 2
  • 40
  • 49