Baseline Model Change Event Replacement

I think that I want to do quite simply, I just do not know how to do it. I would like to start my own event when one of my model attributes changes to transfer some data to the event handler (whether the change was an increase or decrease in value).

Basically, I want my handler to do this in a view

handler: function(increased) { if(increased) { alert("the value increased") } else { alert("the value decreased") } } // ... this.model.on("change:attr", this.handler, this); 
+8
javascript events backbone-events
source share
3 answers

Here you go: you listen mostly to change:myvar . When a change occurs, you use your previous() model to get the old value. Depending on whether it has been increased or decreased, you fire an appropriate event. You can listen to these events as shown in initialize() .

 (function($){ window.MyModel = Backbone.Model.extend({ initialize: function () { this.on('change:myvar', this.onMyVarChange); this.on('increased:myvar', function () { console.log('Increased'); }); this.on('decreased:myvar', function () { console.log('Decreased'); }); }, onMyVarChange: function () { if (this.get('myvar') > this.previous('myvar')) { this.trigger('increased:myvar'); } else { this.trigger('decreased:myvar'); } } }); window.mymodel = new MyModel({myvar: 1}); mymodel.set({myvar: 2}); mymodel.set({myvar: 3}); mymodel.set({myvar: 1}); })(jQuery);​ 

The launch above will print “Increased”, “Increased”, “Decreased” on your console.

+12
source share

Just look at previousAttributes()

Then you can compare:

 If(this.get(attr) > this.previousAttributes()[attr]){ console.log('bigger'); } else { console.log('smaller'); } 

If you use this in your change event handler, you are all set up. No need for a custom trigger or a ton of code.

EDIT

This is from my Backbone.Validators project and how I get a list of all the attributes that changed during the validation step:

 var get_changed_attributes = function(previous, current){ var changedAttributes = []; _(current).each(function(val, key){ if(!_(previous).has(key)){ changedAttributes.push(key); } else if (!_.isEqual(val, previous[key])){ changedAttributes.push(key); } }); return changedAttributes; }; 

This requires Underscore 1.3.1 because it uses _.has . If you cannot upgrade, that is easy to replace. In your case, you will pass this.previousAttributes() and this.attributes

+2
source share

What if you fire your own custom event after listening to the change event?

 handler: function(increased) { this.model.trigger('my-custom-event', stuff, you, want); }, myHandler: function(stuff, you, want){ // Do it... } // ... this.model.on("change:attr", this.handler, this); this.model.on('my-custom-event, this.myHandler, this); 
0
source share

All Articles