Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
149
rated 0 times [  155] [ 6]  / answers: 1 / hits: 25377  / 11 Years ago, tue, december 24, 2013, 12:00:00
var max = this.collection.max(function(player) {
return player.get('points');
});


I spent a few hours playing with backbone.js trying to figure out how to check if my max model changes, it was nearly impossible, so I decided to set the models cid as a data-attribute now it seems impossible to check if the data-attribute changes?



I set the attribute like so,



$(this.$el).attr('data-id', max.cid)


When my app re-renders the data-attribute may or may not get a new value. I am really not sure how to check if it changes, I have seen a lot of various dirty hacks and setInterval functionality but nothing that seemed very clean, so I am hoping someone knows a nice clean way to do this?



Basically I just want control over the element if it renders new data from another model (meaning if another model takes the max value), I need to check the id to confirm that the model is a new version, and run an animation or render it showing that it is a new model.


More From » jquery

 Answers
12

First of all the data- attribute - while you can access the data attribute using .attr or .prop, data is stored in an object $.cache on page load and manipulated thereafter. The attributes data-* are NEVER updated.



To set data



$el.data('id', max.cid);


To get data



var something = $el.data('id');


Unfortunately there is no way to listen for a change in data without using setInterval as previously explored in this similar question.



That said, if it's only YOUR code that's updating the data, a logical solution is this:



Set up an event



$el.on('datachange', function(){
// procedure here
});


Then either trigger it when you update the data



$el.data('id', max.cid).trigger('datachange');


or write your own data function that uses .data() and triggers the event



$.fn.mydata=function(key, variable){
$(this).data(key, variable).trigger('datachange');
}

$el.mydata('id', max.cid);





Example: http://jsfiddle.net/Qn9H6/



$(#test).on('datachange', function(e, key){
$('#feedback').hide().text('data ' + key + ' was changed to ' + $(this).data(key)).fadeIn(1000);
});

$.fn.mydata=function(key, variable){
if ($(this).data(key)!=variable){ // check if it's changed
$(this).data(key, variable).trigger('datachange', key);
}else{
console.log('data wasn't changed');
}
}

$('button').click(function() {
$(#test).mydata('id', $(this).text());
})

$(#test).mydata('id', 456);

[#73564] Monday, December 23, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
zayne

Total Points: 366
Total Questions: 98
Total Answers: 98

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
;