hay / stapes

the Javascript MVC microframework that does just enough
http://hay.github.io/stapes
MIT License
443 stars 54 forks source link

Added nochange event on attribute set #26

Closed rburgt closed 11 years ago

hay commented 11 years ago

I don't think adding a nochange event is the best way forward. This implies that you'll also need nomutate, noupdate, etcetera events and defies the purpose of Stapes as a lightweight library without a lot of voodoo.

If you really want to have this functionality you could monkey-patch Stapes with a new set method that triggers a nochange event for all attributes that are the same. Something like this would work (i've tested it on the unit test suite)

(function() {
    var oldSet = Stapes._.Module.set;

    Stapes.extend({
        set : function(key, val) {
            // We'll only make it work for key/value pairs
            if (typeof key === 'string') {
                if (this.get(key) === val) {
                    this.emit('nochange', key);
                    this.emit('nochange:' + key, val);
                }
            }

            return oldSet.apply(this, arguments);
        }
    });

    var obj = Stapes.create();
    obj.on('nochange:foo', function(data) {
        console.log('nochange for foo!');
    });
    obj.set('foo', 1);
    obj.set('foo', 1);
})();

The nochange:foo event will only be triggered when the foo attribute is the same.