backbone-is-required.js 1.38 KB
define(function(require) {
    'use strict';
    var _ = require('underscore');
    var Backbone = require('backbone');

    function wrapMethod(MethodHolder, methodName, methodCreator) {
        MethodHolder[methodName] = methodCreator(methodName, MethodHolder[methodName]);
    }

    Backbone.isRequiredMixin = function(ModelClass) {
        wrapMethod(ModelClass.prototype, 'toJSON', function(methodName, origMethod) {
            return function(options) {
                var data = origMethod.apply(this, arguments);
                delete data._isRequired;
                return data;
            };
        });
        wrapMethod(ModelClass.prototype, 'parse', function(methodName, origMethod) {
            return function(data, options) {
                data = _.clone(data);
                delete data._isRequired;
                return origMethod.apply(this, arguments);
            };
        });
        wrapMethod(ModelClass.prototype, 'initialize', function(methodName, origMethod) {
            return function(data, options) {
                origMethod.apply(this, arguments);
                if (data && data._isRequired !== undefined) {
                    this.set('_isRequired', data._isRequired);
                }
            };
        });
        return ModelClass;
    };
    Backbone.isRequiredMixin.validationChecker = function() {
        return this.get('_isRequired');
    };
});