문제

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.

도움이 되었습니까?

해결책

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);
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top