rivets-backbone-adapter-brainfood.js 2.46 KB
define(function(require) {
    'use strict';
    var module = require('module');
    var Backbone = require('backbone');
    var rivets = require('rivets');

    var separator = module.config().separator || ':';
    var adapter = rivets.adapters[separator] = (function(Model, Collection, collectionEvents) {
        var observableFactory = function observableFactory(eventMethodName) {
            return function (obj, keypath, callback) {
                var eventMethod = obj[eventMethodName];
                if (obj instanceof Collection) {
                    eventMethod.call(obj, collectionEvents, callback);
                } else if (obj instanceof Model) {
                    eventMethod.call(obj, keypath === '*' ? 'change' : ('change:' + keypath), callback);
                    if (keypath !== '*') {
                        var value = obj.get(keypath);
                        if (value instanceof Collection) {
                            value[eventMethodName].call(value, collectionEvents, callback);
                        }
                    }
                }
            };
        };
        return {
            observe: observableFactory('on'),
            unobserve: observableFactory('off'),
            get: function get(obj, keypath) {
                if (obj instanceof Model) {
                    if (keypath === '*') {
                        return obj.attributes;
                    }
                } else if (obj instanceof Collection) {
                    if (keypath === '*') {
                        return obj.models;
                    }
                } else {
                    return;
                }
                return obj.get(keypath);
            },
            set: function set(obj, keypath, value) {
                if (obj instanceof Model) {
                    if (keypath === '*') {
                        obj.set(value);
                    } else {
                        obj.set(keypath, value);
                    }
                } else if (obj instanceof Collection) {
                    if (keypath === '*') {
                        obj.set(value);
                    } else {
                        var existing = obj.get(keypath);
                        if (existing) {
                            obj.set(value, {at: obj.indexOf(existing)});
                        }
                    }
                }
            },
        };
    })(Backbone.Model, Backbone.Collection, 'add remove reset sort');
    return adapter;
});