Example #1
0
test('data-bind', function() {
  class SomeView extends Backbone.View {
    static initClass() {
      this.prototype.els = {
        '#name': '$name',
        '#title': '$title'
      }
    }

    template({name, title}) {
      return `\
<i id='name' data-bind='name'>${name}</i>
<i id='title' data-bind='title'>${title}</i>\
`
    }

    format(attr, value) {
      if (attr === 'title') {
        return 'formatted'
      } else {
        return value
      }
    }
  }
  SomeView.initClass()
  const model = new Backbone.Model()
  const view = new SomeView({model})
  view.render()
  model.set('name', 'ryanf')
  equal(view.$name.html(), 'ryanf', 'set template to model data')
  model.set('name', 'jon')
  equal(view.$name.html(), 'jon', 'element html kept up-to-date')
  model.set('title', 'engineer')
  equal(view.$title.html(), 'formatted', 'formatting applied')
})
Example #2
0
define(function(require, exports, module) {
    var $           = require('jquery'),
        _           = require('underscore'),
        Backbone    = require('backbone');

    var Flowchart = Backbone.Model.extend({

        defaults: {
            nodes: null,
            arrows: null,
            title: '',
        },

        initialize: function() {
            _(this).bindAll('addNode', 'removeNode', 'updateNode', 'addArrow', 'removeArrow');

            this.setAsArray('nodes', 'arrows');
        },

        // Modification methods.

        addNode: function(attributes) {
            this.get('nodes').push({
                id: attributes.id,
                data: attributes.data
            });

            this.trigger('change');
        },

        removeNode: function(id) {
            var index = _(this.get('nodes')).indexOf(_(this.get('nodes')).findWhere({ id: id }));

            if(index !== -1) {
                this.get('nodes').splice(index, 1);

                this.trigger('change');
            }
        },

        updateNode: function(attributes) {
            var index = _(this.get('nodes')).indexOf(_(this.get('nodes')).findWhere({ id: attributes.id }));

            this.get('nodes')[index].data = attributes.data;

            this.trigger('change');
        },

        addArrow: function(attributes) {
            this.get('arrows').push({
                id: attributes.id,
                from: attributes.from,
                to: attributes.to
            });

            this.trigger('change');
        },

        removeArrow: function(id) {
            var index = _(this.get('arrows')).indexOf(_(this.get('arrows')).findWhere({ id: id }));

            if(index !== -1) {
                this.get('arrows').splice(index, 1);

                this.trigger('change');
            }
        },

        setAsArray: function() {
            _(arguments).each(function(argument, index) {
                if(_(argument).isString()) {
                    if(!this.get(argument)) this.set(argument, []);
                }
            }.bind(this));
        },
    });

    return Flowchart;
});
Example #3
0
var Backbone = require("Backbone");

var AuthLogin = Backbone.Model.extend({
  urlRoot: "https://user.muxixyz.com/api/login/",
  default: {
    username: "",
    password: ""
  }
});

module.exports = AuthLogin;
Example #4
0
const Band = Backbone.Model.extend({
  urlRoot: `https://baas.kinvey.com/appdata/kid_HyAproyt/bands`,
  idAttribute: '_id',
  defaults: {
    name: '',
    imgURL: '',
    votes: 0,
    spotifyURL: '',
    uri: ''
  },
  voteForBand: function() {
    return new Promise((resolve, reject) => {
      store.session.addVoteFor(this.get('_id'))

      let votes = this.get('votes')
      votes++
      this.set('votes', votes)

      let vote = new Vote()

      vote.save({
        bandId: this.get('_id'),
        userName: store.session.get('username')
      }, {
        success: (voteResponse) => {
          resolve(this.get('votes'))
          this.trigger('update')
        },
        error: function() {
          reject()
          throw new Error('CREATING VOTE FAILED')
        }
      })
    })

  },
  removeVote: function() {
    $.ajax(`https://baas.kinvey.com/appdata/${store.settings.appKey}/votes?query={"bandId":"${this.get('_id')}"}`)
    .then((response) => {
      response.filter(vote => {
        if (vote.userName === store.session.get('username')) {
          return vote
        }
      }).forEach(vote => {
        $.ajax({
          type: 'DELETE',
          url: `https://baas.kinvey.com/appdata/${store.settings.appKey}/votes/${vote._id}`,
          success: (r) => {
            this.set('votes', (this.get('votes') -1))
            store.session.removeVoteFor(vote.bandId)
          },
          error: (e) => {
            console.error('ERROR: ', e);
          }
        })
      })
    })
  },
  getVotes: function() {
    $.ajax(`https://baas.kinvey.com/appdata/${store.settings.appKey}/votes?query={"bandId":"${this.get('_id')}"}`)
    .then((response) => {
      this.set('votes', response.length)
      store.voteBands.foundVotes++
      if (store.voteBands.foundVotes === store.voteBands.data.models.length) {
        store.voteBands.fetching = false
        store.voteBands.data.trigger('update')
      }
    })
    .fail(() => {
      store.voteBands.foundVotes++
    })
  }
})
  describe('Address View Helpers Tests', function () {
    var addressView = require('address.views');
    var addressTemplate = require('text!modules/base/components/address/base.component.address.template.html');

    var StandardAddressModel = Backbone.Model.extend({
      defaults: {
        givenName: 'ben',
        familyName: 'boxer',
        streetAddress: '1234 HappyVille Road',
        extendedAddress: 'Siffon Ville',
        city: "Vancouver",
        region: "BC",
        country: "CA",
        postalCode: "v8v8v8",
        href: 'fakeUrlToPostAddressForm'
      }
    });

    var CountryModel = Backbone.Model.extend({
      defaults: {
        displayName: 'China',
        name: 'CN',
        regionLink: 'http://ep-pd-ad-qa0.elasticpath.net:8080/cortex/geographies/campus/countries/inha=/regions',
        selected: true
      }
    });

    var RegionModel = Backbone.Model.extend({
      defaults: {
        displayName: 'Nunavut',
        name: 'NU',
        selected: true
      }
    });

    before(function () {
      // append templates
      $("#Fixtures").append(addressTemplate);
    });

    after(function () {
      $("#Fixtures").empty();
    });

    describe('function: formatMsgAsList', function () {
      before(function () {
        this.testFn = addressView.__test_only__.formatMsgAsList;
      });

      after(function () {
        delete(this.testFn);
      });

      it('format list into unordered list (ul)', function () {
        var errMsg = ['line1', 'line2', 'line3'];
        expect(this.testFn(errMsg)).to.have.string('<LI>line1</LI><LI>line2</LI><LI>line3</LI>');
      });

      it('format 1 line message as just text', function () {
        var errMsg = ['One line message.'];
        expect(this.testFn(errMsg)).to.be.equal(errMsg[0]);
      });
    });

    describe('function: translateErrorMessage', function () {
      before(function () {
        sinon.stub(ep.logger, 'warn');
        this.testFn = addressView.translateErrorMessage;
      });

      after(function () {
        delete(this.testFn);
        ep.logger.warn.restore();
      });

      it('translate recorded raw message to err message key', function () {
        var errMsg = 'family-name: must not be blank';
        // test doesn't load i18n locale list, thus return back the key
        expect(this.testFn(errMsg)).to
          .equal('addressForm.errorMsg.missingFamilyNameErrMsg');
      });

      it('does not produce duplicate err message keys', function () {
        var errMsg = 'family-name: may not be null; family-name: must not be blank';
        // test doesn't load i18n locale list, thus return back the key
        expect(this.testFn(errMsg)).to
          .eql('addressForm.errorMsg.missingFamilyNameErrMsg');
      });

      it('translate unrecorded raw message to generic error message key', function () {
        var errMsg = 'not a message recorded';
        // test doesn't load i18n locale list, thus return back the key
        expect(this.testFn(errMsg)).to
          .eql('addressForm.errorMsg.generalSaveAddressFailedErrMsg');
      });

      it('translate only recorded raw message, and log unrecorded error message', function () {
        var errMsg = 'family-name: must not be blank; not a message recorded';
        // test doesn't load i18n locale list, thus return back the key
        expect(this.testFn(errMsg)).to
          .eql('addressForm.errorMsg.missingFamilyNameErrMsg');
        expect(ep.logger.warn).to.be.calledWithMatch('not a message recorded');
      });

    });

    describe('helper function: getAddressFormValues', function () {
      before(function () {
        this.model = new StandardAddressModel();
        this.view = new addressView.DefaultAddressFormView({model: this.model});

        this.countryCollection = new Backbone.Collection([
          new CountryModel()
        ]);
        this.countryView = new addressView.DefaultCountriesView({collection: this.countryCollection});

        this.regionCollection = new Backbone.Collection([
          new RegionModel()
        ]);
        this.regionView = new addressView.DefaultRegionsView({collection: this.regionCollection});

        renderViewIntoFixture(this.view);
        $(this.view.regions.countriesRegion).append(this.countryView.render().$el);
        $(this.view.regions.regionsRegion).append(this.regionView.render().$el);

        this.form = addressView.getAddressFormValues();
      });

      after(function () {
        removeRenderedView();
        delete(this.model);
        delete(this.view);
        delete(this.form);
      });

      it('returns a Object', function () {
        expect(this.form).to.be.instanceOf(Object);
        expect(this.form).to.be.not.empty;
      });
      it('has address and name properties', function () {
        expect(this.form).to.have.property('address');
        expect(this.form).to.have.property('name');
      });
      it('saves address related form values into address property', function () {
        var addObj = this.form.address;
        expect(addObj).to.have.property('street-address', this.model.get('streetAddress'));
        expect(addObj).to.have.property('extended-address', this.model.get('extendedAddress'));
        expect(addObj).to.have.property('locality', this.model.get('city'));
        expect(addObj).to.have.property('region', this.regionCollection.at(0).get('name'));
        expect(addObj).to.have.property('country-name', this.countryCollection.at(0).get('name'));
        expect(addObj).to.have.property('postal-code', this.model.get('postalCode'));
      });
      it('saves name related form values into name property', function () {
        var nameObj = this.form.name;
        expect(nameObj).to.have.property('family-name', this.model.get('familyName'));
        expect(nameObj).to.have.property('given-name', this.model.get('givenName'));
      });
    });

    function renderViewIntoFixture(view) {
      view.render();
      $("#Fixtures").append('<div id="renderedView"></div>');
      $("#renderedView").append(view.$el);
    }

    function removeRenderedView() {
      $("#renderedView").remove();
    }
  });
Example #6
0
'use strict';

var Backbone = require("backbone")
  , Template;

Template = {
  urlRoot: '/api/1/templates'
};

module.exports = Backbone.Model.extend(Template);
 /* global module, require, console */
'use strict';
var $ = require('jquery');// (window);
var Backbone = require('backbone');
Backbone.$ = $;

module.exports = Backbone.Model.extend({
  urlRoot: '/Event',
  defaults: {
    name: '',
    description: '',
    type: '',
    host: '',
    start: null,
    end: null,
    guests: [],
    address: '',
    message: ''
  },
  initialize: function() {
    console.log('A model instance named ' +
    this.get('name') + ' has been created.');
  }
});

Example #8
0
/*
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

/*
 * Copyright (c) 2014, Joyent, Inc.
 */

var Backbone = require('backbone');

var Settings = Backbone.Model.extend({
    url: '/api/settings'
});


module.exports = new Settings();
Example #9
0
var Backbone = require('backbone');

var Paging = Backbone.Model.extend({
  defaults: {
    startIndex: 0,
    numberResults: 100
  }
});

var PagingCollection = Backbone.Collection.extend({
  model: Paging,
});

module.exports = {
  collection: PagingCollection,
  model: Paging
};
Example #10
0
var Session = Backbone.Model.extend({

    // Initialize with negative/empty defaults
    // These will be overriden after the initial checkAuth
    defaults: {
        logged_in: false,
        user_id: '',
    },

    initialize: function(){
        // Singleton user object
        // Access or listen on this throughout any module with app.session.user
        this.user = new User({});
    },


    url: function(){
        return window.app.API + '/auth';
    },

    // Fxn to update user attributes after recieving API response
    updateSessionUser: function( userData ){
        this.user.set(_.pick(userData, _.keys(this.user.defaults)));
    },


    /*
     * Check for session from API 
     * The API will parse client cookies using its secret token
     * and return a user object if authenticated
     */
    checkAuth: function(callback, args) {
        var self = this;
        this.fetch({ 
            success: function(mod, res){
                if(res && !res.error){
                    self.updateSessionUser(res);
                    self.set({ logged_in : true });
                    if('success' in callback) callback.success(mod, res);    
                } else {
                    self.set({ logged_in : false });
                    if('error' in callback) callback.error(mod, res);    
                }
            }, error:function(mod, res){
                self.set({ logged_in : false });
                if('error' in callback) callback.error(mod, res);    
            }
        }).complete( function(){
            if('complete' in callback) callback.complete();
        });
    },


    /*
     * Abstracted fxn to make a POST request to the auth endpoint
     * This takes care of the CSRF header for security, as well as
     * updating the user and session after receiving an API response
     */
    postAuth: function(opts, callback, args){
        var self = this;
        var postData = _.omit(opts, 'method');
        console.log(postData);
        $.ajax({
            url: this.url() + '/' + opts.method,
            contentType: 'application/x-www-form-urlencoded',
            type: 'POST',
            beforeSend: function(xhr) {
                // Set the CSRF Token in the header for security
                var token = $('meta[name="csrf-token"]').attr('content');
                if (token) xhr.setRequestHeader('X-CSRF-Token', token);
            },
            data: $.param(postData),
            success: function(res){

                if( !res.error ){
                    if(_.indexOf(['login', 'signup'], opts.method) !== -1){

                        self.updateSessionUser( res || {} );
                        self.set({ user_id: res.id, logged_in: true });
                    } else {
                        self.set({ logged_in: false });
                    }

                    if(callback && 'success' in callback) callback.success(res);
                } else {
                    if(callback && 'error' in callback) callback.error(res);
                }
            },
            error: function(mod, res){
                if(callback && 'error' in callback) callback.error(res);
            }
        }).complete( function(){
            if(callback && 'complete' in callback) callback.complete(res);
        });
    },


    login: function(opts, callback, args){
        this.postAuth(_.extend(opts, { method: 'login' }), callback);
    },

    logout: function(opts, callback, args){
        this.postAuth(_.extend(opts, { method: 'logout' }), callback);
    },

    signup: function(opts, callback, args){
        this.postAuth(_.extend(opts, { method: 'signup' }), callback);
    },

    removeAccount: function(opts, callback, args){
        this.postAuth(_.extend(opts, { method: 'remove_account' }), callback);
    }

});
var FreezeModel = Backbone.Model.extend({

    /**
     * Constructor for the immutable model.
     *
     * Uses all the default backbone model constructor mechanisms, and then
     * replaces all the methods it uses with the immutable versions.
     *
     * @param attributes
     * @param options
     */
    constructor: function (attributes, options) {
        // Call the normal backbone collection constructor
        Backbone.Model.prototype.constructor.call(this, attributes, options);

        // Set the functions that the constructor needs to work to no longer work if they would 
        // be modifying the model, after the constructor is done using it
        _.each(postConstructErroringMethods, function(message, methodName) {
            this[methodName] = function() {
                errorFunction(message);
            }
        }, this);
    },

    /**
     * Returns a mutable model that is a copy of this immutable one.
     *
     * @returns {Backbone.Model}
     */
    clone: function() {
        return new Backbone.Model(this.attributes);
    },

    /**
     * On is a no op because the construction of a collection uses on after
     * construction of the model. 
     */
    on: function() {},


    /**
     * Off is a no op because the construction of a collection uses off after
     * construction of the model. 
     */
    off: function() {}


    /* Methods to leave alone, because they don't affect the contents of the model:
     initialize,
     toJSON,
     get,
     escape,
     parse,
     _validate
     */

});
Example #12
0
    $ = require('jquery'),
    Backbone = require('backbone'),
    goodsTpl = require('../templates/_entityGoods.tpl');
var config = require('../conf');

Backbone.$ = $;

//** 模型
var Goods = Backbone.Model.extend({
    idAttribute: '_id',
    urlRoot: config.api.host + '/protect/goods',
    defaults: {},
    validation: {
        'name': {
            minLength: 2,
            msg: '长度至少两位'
        },
        'barcode': {
            required: true,
            msg: '请输入运营商系统的物料号'
        }
    },
});

//** 主页面
exports = module.exports = FormView.extend({

    el: '#exportForm',

    modelFilled: false,
Backgrid.Extension.AdvancedFilter.FilterStateModel = Backbone.Model.extend({
  defaults: {
    activeFilterId: null,
    columnCollection: null,
    dataCollection: null,
    filterCollection: null
  },

  /**
   * @method getActiveFilter
   * @return {Backgrid.Extension.AdvancedFilter.FilterModel}
   */
  getActiveFilter: function() {
    var self = this;
    var filterId = self.get("activeFilterId");
    return self.get("filterCollection").get(filterId);
  },

  /**
   * @method setActiveFilter
   * @param filterToActivate
   */
  setActiveFilter: function(filterToActivate) {
    var self = this;

    // Remove saved state from current filter
    self.trigger("filter:save");

    var filterId;
    if (filterToActivate instanceof Backgrid.Extension.AdvancedFilter.FilterModel) {
      filterId = filterToActivate.cid;
    }
    else {
      filterId = filterToActivate;
    }

    if (self.get("filterCollection").get(filterId)) {
      self.set("activeFilterId", filterId);
    }
  },

  /**
   * @method getFilterableColumns
   */
  getFilterableColumns: function() {
    var self = this;
    var columns = self.get("columnCollection");
    if (!columns) {
      return {};
    }

    var filterAbleColumns = columns.filter(function(col) {
      return _.has(FilterTypes, col.get("filterType"));
    });

    var result = {};
    _.each(filterAbleColumns, function(col) {
      result[col.get("name")] = {
        label: col.get("label"),
        filterType: col.get("filterType")
      };
    });

    return result;
  },

  /**
   * @method getMatchers
   * @param {String} type
   */
  getMatchers: function(type) {
    var filterType = FilterTypes[type];

    if (!filterType) {
      return {};
    }

    var result = {};
    _.each(filterType.matchers, function(matcher) {
      result[matcher] = {
        label: FilterMatchers[matcher].name
      };
    });

    return result;
  },

  /**
   * @method getInputTypeInfoForMatcher
   * @param matcher
   * @return {string}
   */
  getInputTypeInfoForMatcher: function(matcher, filterType) {
    return {
      valueType: FilterMatchers[matcher].valueType,
      inputType: FilterTypes[filterType].inputType
    };
  },

  /**
   * @method getValueParser
   * @param filterType
   * @return {Function}
   */
  getValueParser: function(filterType) {
    return FilterTypes[filterType].parser;
  }
});
Example #14
0
const Base = Backbone.Model.extend({

  /**
   * Used when parsing a model to support a root-level key.
   *
   * @property {String} payloadRootName
   */
  payloadRootName: '',

  hasLoadedOnce: false,

  initialize: function(options) {
    this.listenToOnce(this, 'change', this.markAsLoadedOnce);
  },

  markAsLoadedOnce: function() {
    this.hasLoadedOnce = true;
  },

  /**
   * Provides basic parsing for model instances.
   *
   * Implements behavior of `payloadRootName`.
   *
   * @param  {Object} payload Raw JSON-parsed payload.
   * @return {Object}
   */
  parse: function(payload) {
    const root = this.payloadRootName;
    return root && _.has(payload, root) ? payload[root] : payload;
  },

  /**
   * Generates a view-ready copy of the model.
   *
   * By default, this is identical to `toJSON`, but should be overridden
   * to provide custom behavior.
   *
   * @return {Object}
   */
  toView: function() {
    return Backbone.Model.prototype.toJSON.apply(this, arguments);
  },
  /**
   * Easily get tag props by name
   * @param {String}
   * @returns {*}
   */
  getTag: function(tagName) {
    return _.get(this.attributes, 'tags.' + tagName, '');
  },

  setTag: function(tagName, value) {
    if (!this.attributes.tags) {
      this.attributes.tags = {};
    }
    this.attributes.tags[tagName] = value;
  },

  substituteString: function(str, replacements) {
    return str.replace(/%\w+%/g, function(all) {
      return replacements[all] || all;
    });
  }
});
Example #15
0
module.exports = Backbone.Model.extend({

  initialize: function (attrs, opts) {
    if (!opts.layerInfowindowModel) throw new Error('layerInfowindowModel is required');
    this._layerInfowindowModel = opts.layerInfowindowModel;

    this._generateSchema();
    this._initBinds();
  },

  _initBinds: function () {
    this.bind('change', _.debounce(this._onChange.bind(this), DEBOUNCE_TIME), this);
  },

  _onChange: function () {
    var self = this;

    _.each(this.changed, function (val, key) {
      // if the attr doesn't exist in the infowindowModel it will be created, BOOM
      self._layerInfowindowModel.set(key, val);
    });
  },

  _generateSchema: function () {
    this.schema = {};

    var type = this._layerInfowindowModel.get('template_name');

    if (type !== '' && type !== 'none') {
      if (this._layerInfowindowModel.has('width')) {
        this.schema.width = {
          type: 'Number',
          title: _t('editor.layers.infowindow.style.size.label'),
          validators: ['required', {
            type: 'interval',
            min: 200,
            max: 400
          }],
          editorAttrs: {
            help: _t('editor.layers.infowindow.style.size.help')
          }
        };
      }
    }

    if (type === 'infowindow_color') {
      this.schema.headerColor = {
        type: 'Fill',
        title: _t('editor.layers.infowindow.style.header-color'),
        options: [],
        dialogMode: DialogConstants.Mode.FLOAT,
        editorAttrs: {
          color: {
            hidePanes: ['value']
          }
        },
        validators: ['required']
      };
    }
  }

});
Example #16
0
'use strict';
var Backbone = require('backbone');

var Model = Backbone.Model.extend({
    defaults: {
		id:0,
		jcre:null,
		log_level:0,
		origin:'',
		scope:'',
		loguser:'',
		domaine:0,
		message_number:500,
		log_message:'',
		otherinfo:{}
    }
});

module.exports = Model;
Example #17
0
export default Backbone.Model.extend({
  idAttribute: 'id',

  urlRoot () {
    return window.baseUrl + '/api/metrics';
  },

  sync (method, model, options) {
    const opts = options || {};
    if (method === 'create') {
      _.defaults(opts, {
        url: this.urlRoot() + '/create',
        type: 'POST',
        data: _.pick(model.toJSON(), 'key', 'name', 'description', 'domain', 'type')
      });
    }
    if (method === 'update') {
      _.defaults(opts, {
        url: this.urlRoot() + '/update',
        type: 'POST',
        data: _.pick(model.toJSON(), 'id', 'key', 'name', 'description', 'domain', 'type')
      });
    }
    if (method === 'delete') {
      _.defaults(opts, {
        url: this.urlRoot() + '/delete',
        type: 'POST',
        data: { ids: this.id }
      });
    }
    return Backbone.ajax(opts);
  }
});
Example #18
0
var Backbone = require('backbone'),
    api = require('./')("https://artsy.net/api");

// Copy & paste the xapp token Artsy gives you. You can find it here:
// https://developers.artsy.net/start
var xappToken = '';

// Models
var Artwork = Backbone.Model.extend({
});
var Artists = Backbone.Collection.extend({
});

// Add the xapp token to every request
api.intercept(function(req) {
  req.withRequestOptions({ headers: { 'X-Xapp-Token': xappToken } });
});

// Fetch the first artwork and first artist
api.get(Artwork, 'artworks[0]', function(err, artwork) {
  api.get(Artists, 'artworks[0].artists.artists', function(err, artists) {
    console.log('The first public artwork at Artsy is ' +
      artwork.get('title') + ' by ' + artists.pluck('name').join(', ')
    );
  });
});
Organizations.Model = Backbone.Model.extend({
  url: function() {
    return settings.api.baseurl + '/orgs/' + this.id + '.jsonp/?callback=?';
  },

  parse: function(data) {
    // Format dollar amounts nicely
    if (data && data.org_grants_funded) {
      data.amount_funded = numeral(data.org_grants_funded).format('0,0[.]00');
    }
    if (data && data.org_grants_received) {
      data.amount_received = numeral(data.org_grants_received).format(
        '0,0[.]00'
      );
    }

    if (
      !data.org_grants_funded ||
      data.org_grants_received > data.org_grants_funded
    ) {
      data.show_first = 'received';
    }

    if (
      !data.org_grants_received ||
      data.org_grants_received < data.org_grants_funded
    ) {
      data.show_first = 'funded';
    }

    data.slug = util.slugify(data.title);

    if (data.field_ntee) {
      _.each(data.field_ntee.und, function(ntee) {
        ntee.slug = util.slugify(ntee.name);
      });
    }

    return data;
  },
});
Example #20
0
File: model.js Project: ioPanda/erp
import {Model} from 'backbone';

export default Model.extend({
	defaults:{
		
	}
});
Example #21
0
File: dataset.js Project: afs/jena
  function( require ) {
    "use strict";

    var Marionette = require( "marionette" ),
        Backbone = require( "backbone" ),
        _ = require( "underscore" ),
        fui = require( "app/fui" ),
        sprintf = require( "sprintf" ),
        Task = require( "app/models/task" );

    /**
     * This model represents the core representation of the remote Fuseki
     * server. Individual datasets have their own model.
     */
    var Dataset = Backbone.Model.extend( {
      initialize: function( datasetDescription, baseURL, mgmtURL ) {
        this.set( datasetDescription );
        this.set( {
                    baseURL: baseURL,
                    mgmtURL: mgmtURL,
                    counts: {},
                    countPerformed: false,
                    counting: false,
                    statistics: false
                  } );
      },

      /* x is the empty object if baseURL is "" 
       * Ensure it is always a string.
       */
      getStr: function(key) {
        var x = this.get( key );
        return jQuery.isEmptyObject(x) ? "" : x ;
      },
  
      baseURL: function() {
        return this.getStr( "baseURL" );
      },

      mgmtURL: function() {
        return this.getStr( "mgmtURL" );
      },

      mgmtActionURL: function() {
        return this.get( "mgmtURL" ) + this.name();
      },

      statisticsURL: function() {
        return sprintf( "%s/$/stats%s", this.baseURL(), this.name() );
      },

      name: function() {
        return this.get( "ds.name" );
      },

      services: function() {
        return this.get( "ds.services" );
      },

      countPerformed: function() {
        return this.get( "countPerformed" );
      },

      counts: function() {
        return this.get( "counts" );
      },

      serviceTypes: function() {
        return _.map( this.services(), function( s ) {return s["srv.type"];} );
      },

      /** Return a descriptive data-structure listing all this datasets services */
      servicesDescription: function() {
        var description = [];
        var self = this;

        _.each( this.services(), function( s ) {
          _.each( s["srv.endpoints"], function( e ) {
            description.push( {label: s["srv.description"],
                               url: self.datasetEndpointURL( e )
                              } );
          } );
        } );

        description.sort( function( d0, d1 ) {
          return (d0.label < d1.label) ? -1 : (d0.label > d1.label ? 1 : 0);
        } );

        return description;
      },

      /** Return the first service that has the given type */
      serviceOfType: function( serviceType ) {
        return _.find( this.services(), function( s ) {
          return s["srv.type"] === serviceType;
        } );
      },

      /** Return the first endpoint of the first service that has the given type */
      endpointOfType: function( serviceType ) {
        var service = this.serviceOfType( serviceType );
        return service && _.first( service["srv.endpoints"] );
      },

      /* Return URL for a service of a given type or null, if no such service */
      endpointURL: function( serviceType ) {
        var endpoint = this.endpointOfType( serviceType );
        return endpoint ? this.datasetEndpointURL( endpoint ) : null;
      },

      /** Return the URL for the given endpoint */
      datasetEndpointURL: function( endpoint ) {
        return sprintf( "%s%s/%s", this.baseURL(), this.name(), endpoint );
      },

      /** Return the sparql query URL for this dataset, if it has one, or null */
      queryURL: function() {
        return this.endpointURL( "Query" ) ;
      },

      /** Return the sparql query URL for this dataset, if it has one, or null */
      quadsURL: function() {
        return this.endpointURL( "Quads" ) ;
      },

      /** Return the sparql update URL for this dataset, if it has one, or null */
      updateURL: function() {
        return this.endpointURL( "Update" ) ;
      },

      /** Return the GSP write URL for this dataset, if it has one, or null */
      graphStoreProtocolURL: function() {
        if ( this.endpointURL( "GSP" ) )
            // Old name
            return this.endpointURL( "GSP" ) ;
        return this.endpointURL( "GSP_RW" ) ;
      },

      /** Return the GSP read URL for this dataset, if it has one, or null */
      graphStoreProtocolReadURL: function() {
        return this.endpointURL( "GSP_R" ) ;
      },

      /** Return the upload URL for this dataset, if it has one, or null */
      uploadURL: function( graphName ) {
        if (this.graphStoreProtocolURL() !== null) {
          return sprintf( "%s%s", this.graphStoreProtocolURL(), (graphName === "default" ? "" : ("?graph=" + graphName) ));
        }
        else {
          return null;
        }
      },

      /** Perform the action to delete the dataset. Returns the Ajax deferred object */
      deleteDataset: function() {
        return $.ajax( {
          url: this.mgmtActionURL(),
          type: 'DELETE'
        } );
      },

      /** Perform the action of taking a backup of this dataset */
      backupDataset: function() {
        var backupURL = sprintf( "%s/$/backup%s", this.baseURL(), this.name() );
        var ds = this;

        return $.ajax( {
          url: backupURL,
          type: 'POST'
        } )
          .done( function( taskDescription ) {
            new Task( ds, "backup", taskDescription );
          } );
      },

      /**
       * Request the statistics for this dataset, and return the promise object for the callback.
       * @param keep If truthy, and we have existing statistics, re-use the existing stats
       * */
      statistics: function( keep ) {
        var self = this;
        var currentStats = this.get( "statistics" );

        if (currentStats && keep) {
          return $.Deferred().resolveWith( null, currentStats );
        }
        else {
          return $.getJSON( this.statisticsURL() )
                  .then( function( data ) {
                    self.set( "statistics", data );
                    return data;
                  } );
        }
      },

      /** Perform a count query to determine the size of the dataset. Changes the size property when done,
       * but also returns the JQuery promise object used to monitor the query response */
      count: function() {
        var self = this;
        var query1 = sprintf( "select (count(*) as ?count) {?s ?p ?o}" );
        var query2 = sprintf( "select ?g (count(*) as ?count) {graph ?g {?s ?p ?o}} group by ?g" );

        self.set( "counting", true );

        var updateCount = function( model, result, graph ) {
          var n = parseInt( result.count.value );
          var counts = _.extend( {}, model.get( "counts" ) );
          counts[graph] = n;
          model.set( "counts", counts );
        };

        $.getJSON( self.queryURL(), { query: query1 } )
         .done( function( data ) {
           updateCount( self, data.results.bindings[0], "default graph" );

           $.getJSON( self.queryURL(), { query: query2 } )
            .done( function( data ) {
              _.each( data.results.bindings, function( binding ) {
                if (binding.g) {
                  updateCount( self, binding, binding.g.value );
                }
              } );
            } );

           self.set( {countPerformed: true, counting: false} );
         } );
      },

      /**
       * Fetch the content of the given graph as Turtle. Return the jQuery promise
       * object for the Ajax call.
       */
      fetchGraph: function( graphName ) {
        return $.ajax( this.graphStoreProtocolReadURL(),
                       {method: "get",
                        headers: {Accept : "text/turtle; charset=utf-8"},
                        dataType: "html",
                        data: {graph: graphName}
                       } );
      },

      /**
       * Put the given Turtle content back to the server using the given graph name
       */
      putGraph: function( turtle, graphName ) {
        return $.ajax( sprintf( "%s?graph=%s", this.graphStoreProtocolURL(), graphName ),
                       {method: "put",
                        dataType: "json",
                        data: turtle,
                        contentType: "text/turtle; charset=uft-8"
                       } );
      }

    } );

    return Dataset;
  }
Example #22
0
var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');


var Messages = Backbone.Model.extend({
  idAttribute: '_id',
  defaults: {
    content:'default content',
    time:'default'
  }
});

module.exports= Messages;
var Session = Backbone.Model.extend({
  defaults: {
    gatewaydUrl: '',
    sessionKey: '',
    lastLogin: 0,
    credentials: 'ABC' // Base64
  },

  validationRules: {
    gatewaydUrl: {
      type: 'string',
      minLength: 1,
      isRequired: true
    },
    sessionKey: {
      type: 'string',
      minLength: 1,
      isRequired: true
    },
    lastLogin: {
      type: 'number', // milliseconds since 1970/01/01
      isRequired: true
    },
    credentials: {
      type: 'string',
      minLength: 1,
      isRequired: true
    }
  },

  initialize: function() {
    _.bindAll(this);

    this.set('userModel', new UserModel());

    adminDispatcher.register(this.dispatchCallback);
  },

  dispatchCallback: function(payload) {
    var handleAction = {};

    handleAction[sessionConfigActions.login] = this.login;
    handleAction[sessionConfigActions.logout] = this.logout;
    handleAction[sessionConfigActions.restore] = this.restore;

    if (!_.isUndefined(handleAction[payload.actionType])) {
      handleAction[payload.actionType](payload.data);
    }
  },

  validationErrors: [],

  testValid: function(value, attr, rules) {
    if (_.isNull(value) && !rules[attr].isRequired) {
      return true;
    } else if (_.isUndefined(value)) {
      this.validationErrors.push(attr + ' is undefined');

      return false;
    }

    var isValid = false;
    var minLength = rules[attr].minLength;

    if (typeof value === 'number') {
      isValid = !isNaN(value);
    } else if (typeof value === 'string') {
      isValid = !_.isEmpty(value) && value.length >= minLength;
    } else if (_.isArray(value)) {
      isValid = value.length >= minLength;
    } else if (typeof value === 'object') {
      isValid = !_.isNull(value) && _.keys(value).length >= minLength;
    }

    if (!isValid) {
      this.validationErrors.push(attr + ' is invalid');
    }

    return isValid;
  },

  validate: function(attributes) {
    var _this = this;

    this.validationErrors = [];

    var isValid = _.reduce(attributes, function(accumulator, value, attr) {
      if (_.isUndefined(_this.validationRules[attr])) {
        return accumulator && true;
      }

      if (_this.testValid(value, attr, _this.validationRules)) {
        return accumulator && true;
      }

      return false;
    }, true);


    if (!Object.keys(attributes).length) {
      isValid = false;
    }

    if (!isValid) {
      return this.validationErrors.join(', ');
    }
  },

  // isValid: function() {
  //   this.validate(this.attributes);

  //   return !this.validationError;
  // },

  updateSession: function(gatewaydUrl, sessionKey) {
    this.set({
      gatewaydUrl: gatewaydUrl,
      sessionKey: sessionKey,
      lastLogin: Date.now()
    });
  },

  updateUser: function(name) {
    this.get('userModel').set({
      name: name,
      role: name.split('@')[0],
      isLoggedIn: true
    });
  },

  createCredentials: function(name, sessionKey) {
    var encodedString = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(name + ':' + sessionKey));

    this.set('credentials', 'Basic ' + encodedString);
  },

  login: function(payload) {
    var _this = this;

    this.updateSession(payload.gatewaydUrl, payload.sessionKey);
    this.get('userModel').update(payload.name);
    this.createCredentials(payload.name, payload.sessionKey);

    this.save(null, {
      wait: true,
      url: this.get('gatewaydUrl') + '/v1/users/login',
      contentType: 'application/json',
      data: JSON.stringify({
        name: this.get('userModel').get('name'),
        password: this.get('sessionKey')
      }),
      headers: {
        'Authorization': this.get('credentials')
      }
    })
    .then(function() {
      sessionStorage.setItem('session', JSON.stringify(_this.toJSON()));
    });
  },

  restore: function() {
    var oldSession, oldUser, restoredUser;

    if (sessionStorage.length === 0) {
      return;
    }

    oldSession = sessionStorage.getItem('session');

    this.set(JSON.parse(oldSession));
    oldUser = this.get('userModel');
    restoredUser = new UserModel(oldUser);
    this.set('userModel', restoredUser);
  },

  logout: function() {
    var resetUser;

    this.get('userModel').reset();
    resetUser = this.get('userModel');

    this.set(this.defaults);
    this.set('userModel', resetUser);

    sessionStorage.clear();
    this.trigger('logout');
  },

  isLoggedIn: function() {
    return this.get('userModel').get('isLoggedIn');
  },

  getLogState: function() {
    var logStateMap = {
      true: 'loggedIn',
      false: 'loggedOut'
    };

    return logStateMap[this.isLoggedIn()];
  }
});
Example #24
0
var _ = require('underscore');
var Backbone = require('backbone');
var config = require('../conf');

exports = module.exports = Backbone.Model.extend({
	idAttribute: '_id',
	urlRoot: config.api.host + '/protect/apps',
	defaults: {
		status: {}
	},
	validation: {
		name: {
			required: true,
			msg: '请输入名称(中英文字母)'
		},
		nickname: {
			required: true,
			msg: '请输入编码(字母、_与数字的组合)'
		}
	},
});
Example #25
0
var Backbone = require("Backbone");

var TipItem = Backbone.Model.extend({
	default:{
		title:'',
		url:'',
		views:0,
		likes:0,
		date:''
	}
})

module.exports = TipItem;
  Config = require("./config");

var ResourceList = Backbone.Model.extend({

  urlRoot : Config.baseUrl + '/list',

  initialize: function () {

  },

  toResourceMap: function (links) {
    links = links || this.get('links');

    return _.map(links, function (link) {
      var uriSplit = _.isString(link.href) && link.href.split('?');
      var pathSplit = uriSplit && uriSplit[0] && uriSplit[0].split('/');
      return pathSplit && {
        linkId: link.id,
        href: link.href,
        type: pathSplit.length > 1 && pathSplit[pathSplit.length - 2],
        id: pathSplit.length > 0 && pathSplit[pathSplit.length - 1]
      }
    });
  },

  defaults: function () {
    return { links: [] };
  }
});

module.exports = ResourceList;
Example #27
0
import $ from 'jQuery'
import Backbone from 'Backbone'

var UserModel = Backbone.Model.extend({
	defaults: {
		id: null,
		name: '...',
		points: 0
	}
});

let UserView = Backbone.View.extend({
	tagName: "tr",
	initialize() {
		this.listenTo(this.model, "add change", this.render);
		this.render();
	},
	render() {
		let model = this.model.toJSON();
		let html = `<td>${model.name}</td><td>${model.points}</td>`;

		this.$el.html(html);
		return this;
	}
});

let UserListView = Backbone.View.extend({
	initialize() {
		this.listenTo(this.collection, "add change", this.render);
		this.render();
	},
Example #28
0
module.exports = Backbone.Model.extend({
  defaults: {
    checkLocal: true
  },

  /**
   * @private
   */
  store(data, clb) {
    this.checkStorageEnvironment();

    for (var key in data) localStorage.setItem(key, data[key]);

    if (typeof clb == 'function') {
      clb();
    }
  },

  /**
   * @private
   */
  load(keys, clb) {
    this.checkStorageEnvironment();
    var result = {};

    for (var i = 0, len = keys.length; i < len; i++) {
      var value = localStorage.getItem(keys[i]);
      if (value) result[keys[i]] = value;
    }

    if (typeof clb == 'function') {
      clb(result);
    }

    return result;
  },

  /**
   * @private
   */
  remove(keys) {
    this.checkStorageEnvironment();

    for (var i = 0, len = keys.length; i < len; i++)
      localStorage.removeItem(keys[i]);
  },

  /**
   * Check storage environment
   * @private
   * */
  checkStorageEnvironment() {
    if (this.get('checkLocal') && !localStorage)
      console.warn("Your browser doesn't support localStorage");
  }
});
Example #29
0
var Backbone = require("Backbone");

var AuthInfo = Backbone.Model.extend({
  initialize: function(options) {
    this.options = options;
  },
  url: function() {
    var base = "https://user.muxixyz.com/api/users/";
    return base + this.options.uid + "/";
  }
});

module.exports = AuthInfo;
Example #30
0
module.exports = Backbone.Model.extend({
  defaults: {
    data: "' Welcome to vizard.io\n" +
      "' This diagram will be auto-saved in your browser \n" +
      "' \n" +
      "' For syntax see PlantUML Language Reference Guide:  \n" +
      "' http://plantuml.sourceforge.net/PlantUML_Language_Reference_Guide.pdf \n" +
      "\n" +
      "\n" +
      "A -> B: Example Request\n" +
      "A <-- B: A Response",
    remoteData: null,
    image: null
  },

  initialize: function() {
    this.initDiagram();
  },

  initDiagram: function() {
    _.bindAll(this, 'read', 'update', 'store');
    _.bindAll(this, 'updateImage', 'setDataFromRemote');

    this.image = new DiagramImageModel();

    this.bind('change:remoteData', this.setDataFromRemote);
    this.bind('change:data', this.updateImage);
    this.bind('errorOnFetch', this.updateImage);

    this.fetch({
      error: this.trigger('errorOnFetch')
    });
  },

  //---- PUBLIC
  read: function() {
    if (!this.get('remoteData')) {
      this.remoteLoad();
    }
    return this.get('data');
  },

  update: function(data) {
    this.set('data', data);
  },

  store: function() {
    // console.log("store model: <" + this.id + ">");
    this.save({
      remoteData: this.get('data')
    }, {
      wait: true
    });
  },

  remoteLoad: function() {
    var self = this;
    app.github.loadFile(this.id, function(data) {
      self.set('remoteData', data);
      self.trigger('externalDataLoaded');
    });
  },

  setTitle: function(title) {
    this.set('title', title);
    this.save({
      title: title
    });
  },

  title: function() {
    return this.get('title') || this.get('id');
  },

  //---- PRIVATE
  updateImage: function() {
    this.image.update(this.get('data'));
  },

  setDataFromRemote: function() {
    this.set('data', this.get('remoteData'));
  }
});