0

What is the problem in my bind method using jquery?

Working

var Element = htmlBody.find('tag');
$(Element ).bind('DOMSubtreeModified', function(event) {
    console.log(Element[0]);
    //code come here
});

Not Working

var obj = {};
var tags = ['tag1', 'tag2'];
for (index in tags) {
    obj[index] = htmlBody.find(tags[index]);
    $(obj[index]).bind('DOMSubtreeModified', function(event) {
        console.log(obj[index][0]);
        //  code doe not come here
    });  
}
ahmet
  • 4,955
  • 11
  • 39
  • 64
androidraj
  • 85
  • 2
  • 7
  • You should not use `for... in` to iterate over arrays. In your case, you're probably hitting its `length` property. Use a counter variable instead. – Frédéric Hamidi Oct 17 '13 at 10:00
  • try to use the $.each() / iterate using a temp variable – Arun P Johny Oct 17 '13 at 10:01
  • `DOMSubtreeModified` event is deprecated.. click here for more info: http://stackoverflow.com/questions/6659662/why-is-the-domsubtreemodified-event-deprecated-in-dom-level-3 – Joke_Sense10 Oct 17 '13 at 10:03
  • Aside from some peculiarities in your code, which I assume is a truncated version for demo purposes, it works in a fiddle: http://jsfiddle.net/RoryMcCrossan/HEYXm/ – Rory McCrossan Oct 17 '13 at 10:03
  • also another problem is the buggy use of closure variable `index` in the callback – Arun P Johny Oct 17 '13 at 10:03
  • I think a better approach will be http://jsfiddle.net/arunpjohny/ZyJwH/2/ – Arun P Johny Oct 17 '13 at 10:06
  • which version of jquery your using ? because As of jQuery 1.7, the .on() method is the preferred method for attaching event handlers to a document. For earlier versions, the .bind() method is used for attaching an event handler directly to elements. – dileep kommireddy Oct 17 '13 at 10:06

2 Answers2

1

Try the following:

var obj = {};
var tags = ['tag1', 'tag2'];
$.each(tags, function(idx, item) {
    obj[idx] = htmlBody.find(tags[idx]);
    $(obj[index]).bind('DOMSubtreeModified', function(event) {
        console.log(item);
    });  
});
Flea777
  • 1,012
  • 9
  • 21
1

It is recommended to use the on function instead of bind(). Also you need to iterate through the elements with a for loop.

var obj = {};
var tags = ['tag1', 'tag2'];
for (var i = 0; i < tags.length;i++) {
    obj[i] = htmlBody.find(tags[i]); //not exactly sure what htmlBody.find does
    var item = obj[i][0];
    $(obj[i]).('DOMSubtreeModified', function(event) {
        console.log(item);
    });  
}
Kevin Bowersox
  • 93,289
  • 19
  • 159
  • 189