Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add dynamic events for view?

How can I add dynamic events in my view class in Backbone.js

I have a View Class with

var myViewClass = Backbone.View.extend({
    events: {
        'change select': 'changeSelect',
        'click a.changeLink': 'clearSelect'
    },

    initialize: function() {
        this.delegateEvents({'click select': 'changeSelect'});
    },

    .
    .
    .        
});

This is adding {'click select': 'changeSelect'} event, however somehow {'click a.changeLink': 'clearSelect'} doesn't woek.

anybody knows the solution?

Thanks, Rohan

like image 729
user823400 Avatar asked Jun 30 '11 16:06

user823400


People also ask

How to add a event in a dynamic element in JavaScript?

If you inspect your console, you will see the dynamically created elements injected in your DOM. Now we can add event handlers. To attach event handlers to the dynamically created button, we need to select the button with a class of btn and add an event listener of click .

How to add click event to dynamically added HTML element in JavaScript?

Attaching the event dynamicallyclassName = 'dynamic-link'; // Class name li. innerHTML = dynamicValue; // Text inside $('#links'). appendChild(li); // Append it li. onclick = dynamicEvent; // Attach the event!

How do you add an event listener after an element was created dynamically?

If you create an element via document. createElement , add an event listener, and append it to the DOM. Your events will fire. If you create an element as a string like this: html += "<li>test</li>"`, the elment is technically just a string.

How you can add an event handler?

Right-click the control for which you want to handle the notification event. On the shortcut menu, choose Add Event Handler to display the Event Handler Wizard. Select the event in the Message type box to add to the class selected in the Class list box.


2 Answers

Backbone automatically delegates events from the events attribute of your view. You are overrriding the previously delegated events. You can call $(this.el).delegate(...) but you can also do

this.delegateEvents(_.extend(this.events, {'click select': 'changeSelect'}));
like image 50
Julien Avatar answered Oct 06 '22 17:10

Julien


Since I'm doing this a lot, here is my tiny Backbone extension (based on Julien's answer and my testing):

Backbone.View.prototype.addEvents = function(events) {
  this.delegateEvents( _.extend(_.clone(this.events), events) );
};

Use:

BaseResizable.View = Base.View.extend({
  initialize: function() {
    Base.View.prototype.initialize.call(this);
    this.addEvents({
      'resizestop': 'resizeStop'
    });
  },
  resizeStop: function(event, ui){...}
}

You will have to do addEvents() again if you use undelegateEvents().

like image 29
forresto Avatar answered Oct 06 '22 19:10

forresto