dessi
dessi

Reputation: 27

Bind methods on appended elements

I have an AgentClass with the method this.move. It's working with static objects but when I create new HTML Objects via .append(), I can't use them with my this.move method.

All the new objects have an ID and I want to animate them with the move method.

I often read "live, on, ..." but they all need an event... I don't have such an event on them. They move directly. I tried something like that:

$('.agents').on("load", Agent.move());

But that isn't working... Any ideas?

Codesinppet:

var Agent = function(agentType, xTarget, yTarget) {
    ...
    this.move = function() {
        var id = this.agentId;

        $('.agent#'+id).animate({
            left:"200px"
        }, 1000);
    }
}

And I append them after this like this:

for (deployed = 0; deployed <= agents; deployed++) {
    $('.agents').append('<div class="agent" id="'+deployed+'"></div>');
}

It would be awesome if someone could help me!?

Upvotes: 0

Views: 179

Answers (1)

Shigiang Liu
Shigiang Liu

Reputation: 614

You can use .clone(true) A Boolean indicating whether event handlers and data should be copied along with the elements. The default value is false.

    var agents = 6;
    for (deployed = 0; deployed <= agents; deployed++) {
        $element = $('<div class="agent" id="'+deployed+'"></div>').clone(true);
        $('.agents').append($element);
    }
.agent {
  height:50px;
  width:50px;
  background-color:yellow;
  margin-bottom:10px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<!DOCTYPE html>
<html>
<head>
<title>Agent</title>
</head>

<body>
  <div class="agents">
  </div>
</body>

</html>

But for maximum optimization event is better to use an event handler "on" to monitor the items that will be added after reloading the DOM . This allocates less memory

Upvotes: 3

Related Questions