twitter-flight

Triggering events inside $.each loop


I have a data component, which retrieves an array objects via ajax and sends it over to the ui component for display. May approach is to traverse the the array inside the data component and send each element over to the ui component (instead of sending the entire array).

I am getting an error: Uncaught TypeError: undefined is not function on the line: ths.trigger('dataAdded', value); (see below)

The data component is attached to the document.

this.handleData = function(){
      var ths = this;
        $.ajax({            
        "url": 'url',
        "type": "get",
        "dataType": "json",
        "success": function(data) {
            $.each(data, function(index, value){
                ths.trigger('dataAdded',  value);
            });
        },
        "error": function(jqXHR, status, error) {
            console.log("status:", status, "error:", error);
           // return;
      }
        });
    };

Solution

  • Add '.bind(this);' to the closing $.each braces.

    this.handleData = function(){
          $.ajax({            
            "url": 'url',
            "type": "get",
            "dataType": "json",
            "success": function(data) {
                $.each(data, function(index, value){
                    this.trigger('dataAdded',  value);
                }.bind(this);
            },
            "error": function(jqXHR, status, error) {
                console.log("status:", status, "error:", error);
               // return;
          }
            });
        };
    
    ...
    
    this.after('initialize', function() {
    
    }