Implement Toggle Switching in Backbone.js Events

I would like to implement reversible animation in Backbone, just like we do it in jquery:

$('a.contact').toggle(
function(){
    // odd clicks
},
function(){
    // even clicks
});

My question is how to do this in the syntax of the base event? How do I simulate a function setting function?

events : {
  'click .toggleDiv' : this.doToggle
},

doToggle : function() { ??? }
+5
source share
4 answers

Events in macroblock mode are passed directly to jQuery and give you access to all the standard arguments of the DOM event through the callback method. This way you can easily call the jQuery method to switch the element:


Backbone.View.extend({

  events: {
    "click a.contact": "linkClicked"
  },

  linkClicked: function(e){
    $(e.currentTarget).toggle(
      function() {
        // odd clicks
      },
      function() {
        // even clicks
      }
    );
  }

});
+14
source

I was looking for a solution to this problem, and I just became old-fashioned. I also wanted to be able to find my hideText () method from other views in my application.

, "showmeState" hideText(), showText() , . , , render initialize, .

var View = Backbone.View.extend({
  events: {
    'click': 'toggleContent'
  },
  showmeState: true,
  toggleContent: function(){
    if (this.showmeState === false) {
      this.showText();
    } else {
      this.hideText();
    }
  },
  hideText: function() {
    this.$el.find('p').hide();
    this.showmeState = false;
  },
  showText: function() {
    this.$el.find('p').show();
    this.showmeState = true;
  }
});

var view = new View();
+4

Is the item you want to switch in the view receiving the event? If yes:

doToggle: function() {
  this.$("a.contact").toggle()
}
0
source

In fact, I believe that the only thing that can be done using eventsis to add triggerin order to maintain the actual flow. It seems a little awkward, to be honest, that you need to use the switch in this way.

Backbone.View.extend({

  events: {
    "click .button": "doToggle"
  },

  doToggle: function(e){
    var myEle = $(e.currentTarget);
    $(e.currentTarget).toggle(
      function() {
        // odd clicks
      },
      function() {
        // even clicks
      }
    );
    myEle.trigger('click');
  }

});

Probably just using this

Backbone.View.extend({

  el: '#el',

  initalize: function() {
    this.render();
  },

  doToggle: {
    var myEle = this.$el.find('.myEle');
    myEle.toggle(
      function() {
        // odd clicks
      },
      function() {
        // even clicks
      }
    );
  },

  render: function(e){


    //other stuff

    this.doToggle();

   return this;
  }

});
0
source

All Articles