Search code examples
javascriptbackbone.jsbackbone-events

Backbone.js trigger event blocks the subsequent statement


 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?


Solution

  • 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")
         }
    
       }
     }