TLR
TLR

Reputation: 587

Bind variable method to a click event

I have some trouble with jQuery, I'd like to bind an event to a div generated

myArray = [ {name : 'object1', clickMethod : function(){...}},
          {name : 'object2', clickMethod : function(){...}},
          {name : 'object3', clickMethod : function(){...}}
        ]

In my loop i'd like to do something like this :

for(var i = 0; i < myArray.length; i++) {
  Utils.getGeneratedHtml(myArray[i])
}

//Utils.getGeneratedHtml
Utils.getGeneratedHtml = function(element,selector) {
     var newE = $('<strong />',{id : element.name}).append(element.name);
     newE.click(function(){
        element.clickMethod()
     })

    newE.appendTo(selector);
}

However it looks like the method is not taken in consideration. Should I use classes instead ?

Upvotes: 0

Views: 48

Answers (2)

Esko
Esko

Reputation: 4207

If you want to use an inline function you need to declare it before you want to use it and use var to define it. Note that "." is not allowed in variable names in javascript. Also you are not passing the selector-parameter to your getGeneratedHtml-function. See the example:

var myArray = [{
  name: 'object1',
  clickMethod: function() {
    alert("clicked");
  }
}, {
  name: 'object2',
  clickMethod: function() {
    alert("clicked");
  }
}, {
  name: 'object3',
  clickMethod: function() {
    alert("clicked");
  }
}]

var getGeneratedHtml = function(element, selector) {
  var newE = $('<strong />', {
    id: element.name
  }).append(element.name);
  newE.click(function() {
    element.clickMethod()
  })

  newE.appendTo(selector);
}

for (var i = 0; i < myArray.length; i++) {
  getGeneratedHtml(myArray[i], "div")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>

Upvotes: 1

Justinas
Justinas

Reputation: 43441

First of all var new is not valid and should throw error, because new is keyword.

You need to use live events $('static-el').on('event', 'dynamic-el', function) for your code to work.

Upvotes: 0

Related Questions