AnApprentice
AnApprentice

Reputation: 111040

jQuery how to Bind on a data bind?

<div id="conversations-uCount">0</div>
<script type="text/javascript">
$(document).ready(function() {
    $('#conversations-uCount').data('UnreadIDs', '1');
});
</script>

How can I set a bind so that any time the UnreadIDs changes I can run a function?

Thanks

Upvotes: 5

Views: 1519

Answers (3)

Nick Craver
Nick Craver

Reputation: 630569

In jQuery 1.4.4+ there's an event triggered for this, changeData. If that's the only data you're dealing with on the object, your handler is as simple as:

$('#conversations-uCount').bind("changeData", function() {
  //data changed, do something, for example:
  alert("Data changed!, new value for UnreadIDs: " + $.data(this, 'UnreadIDs'));
});

You can test it out here.

Upvotes: 4

karim79
karim79

Reputation: 342685

I imagine you could do that with a simple plugin:

$.fn.dataTrigger = function(name, value, callback) {
    $(this).data(name, value);
    callback(name, value);
    return this;
};

Then:

$('#conversations-uCount').dataTrigger('UnreadIDs', '1', myFunc);

Demo: http://jsfiddle.net/karim79/q6apA/1/

Upvotes: 1

Amjad Masad
Amjad Masad

Reputation: 4035

Yes there is a function called watch object.watch but its not standard, I think what your looking for can be found here Object.watch() for all browsers?

Upvotes: 0

Related Questions