示例#1
0
文件: tests.js 项目: htom78/peersay
define(function(require,exports, module){
    
    var _        = require('libs/underscore'),
        Backbone = require('libs/backbone'),
        Test     = require('app/models/test');

    module.exports = Backbone.Collection.extend({
        model  : Test,
        url    : 'index.php/tests/lists'
    });
});
示例#2
0
define(function(require) {
  /**
   * Backbone.Collection of instance of AchievementRecord model.
   * @exports models/AchievementRecordList
   */
  var jquery            	= require('libs/jquery'),
      underscore        	= require('libs/underscore'),
      Backbone          	= require('libs/backbone'),
      AchievementRecord     = require('models/AchievementRecord')
      ServerController  	= require('controllers/ServerController');

  AchievementRecordList = Backbone.Collection.extend({

	/** Declaration of the model type this collection aggregates. */
    model: AchievementRecord,

    initialize: function() {

    }
  });
  
  return AchievementRecordList;
});
示例#3
0
export var VisualizationCollection = Backbone.Collection.extend(
    /** @lends VisualizationCollection.prototype */ {
        model: Visualization,

        ///** logger used to record this.log messages, commonly set to console */
        //// comment this out to suppress log output
        //logger              : console,

        url: function() {
            return `${Galaxy.root}api/visualizations`;
        },

        /** Set up.
         *  @see Backbone.Collection#initialize
         */
        initialize: function(models, options) {
            options = options || {};
            //this._setUpListeners();
        },

        //_setUpListeners : function(){
        //},

        // ........................................................................ common queries
        // ........................................................................ ajax
        // ........................................................................ misc
        set: function(models, options) {
            // arrrrrrrrrrrrrrrrrg...
            // override to get a correct/smarter merge when incoming data is partial (e.g. stupid backbone)
            //  w/o this partial models from the server will fill in missing data with model defaults
            //  and overwrite existing data on the client
            // see Backbone.Collection.set and _prepareModel
            var collection = this;
            models = _.map(models, model => {
                var existing = collection.get(model.id);
                if (!existing) {
                    return model;
                }

                // merge the models _BEFORE_ calling the superclass version
                var merged = existing.toJSON();
                _.extend(merged, model);
                return merged;
            });
            // now call superclass when the data is filled
            Backbone.Collection.prototype.set.call(this, models, options);
        },

        /** String representation. */
        toString: function() {
            return ["VisualizationCollection(", [this.historyId, this.length].join(), ")"].join("");
        }
    }
);
示例#4
0
var ConfigSettingCollection = Backbone.Collection.extend(
    {
        model: ConfigSetting,

        /**
         * Save settings as a dictionary of key-value pairs.
         * This function is needed for backwards compatibility.
         */
        to_key_value_dict: function() {
            var rval = {};
            this.each(setting => {
                rval[setting.get("key")] = setting.get("value");
            });

            return rval;
        },

        /**
         * Returns value for a given key. Returns undefined if there is no setting with the specified key.
         */
        get_value: function(key) {
            var s = this.get(key);
            if (s) {
                return s.get("value");
            }

            return undefined;
        },

        /**
         * Set value for a setting.
         */
        set_value: function(key, value, options) {
            var s = this.get(key);
            if (s) {
                return s.set_value(value, options);
            }

            return undefined;
        },

        /**
         * Set default value for a setting.
         */
        set_default_value: function(key, default_value) {
            var s = this.get(key);
            if (s) {
                return s.set("default_value", default_value);
            }

            return undefined;
        }
    },
    {
        /**
         * Utility function that creates a ConfigSettingsCollection from a set of models
         * and a saved_values dictionary.
         */
        from_models_and_saved_values: function(models, saved_values) {
            // If there are saved values, copy models and update with saved values.
            if (saved_values) {
                models = _.map(models, m => _.extend({}, m, { value: saved_values[m.key] }));
            }

            return new ConfigSettingCollection(models);
        }
    }
);
示例#5
0
var JobStatesSummaryCollection = Backbone.Collection.extend({
    model: JobStatesSummary,

    initialize: function() {
        /* By default we wait for a polling update to do model fetch because
           FETCH_STATE_ON_ADD is false to load the application and target components
           as quickly as possible. that said if the polling is turned off
           (!this.active) and collections are added - we need to fetch those still.
           This happens for instance in the single history view where a history is
           shown in a static way and not polled.
        */
        if (FETCH_STATE_ON_ADD) {
            this.on({
                add: model => model.fetch()
            });
        } else {
            this.on({
                add: model => {
                    if (!this.active) {
                        model.fetch();
                    }
                }
            });
        }

        /** cached timeout id for the dataset updater */
        this.updateTimeoutId = null;
        // this.checkForUpdates();
        this.active = true;
    },

    url: function() {
        var nonTerminalModels = this.models.filter(model => {
            return !model.terminal();
        });
        var ids = nonTerminalModels
            .map(summary => {
                return summary.get("id");
            })
            .join(",");
        var types = nonTerminalModels
            .map(summary => {
                return summary.get("model");
            })
            .join(",");
        return `${Galaxy.root}api/histories/${this.historyId}/jobs_summary?ids=${ids}&types=${types}`;
    },

    monitor: function() {
        this.clearUpdateTimeout();
        if (!this.active) {
            return;
        }

        var _delayThenMonitorAgain = () => {
            this.updateTimeoutId = setTimeout(() => {
                this.monitor();
            }, UPDATE_DELAY);
        };

        var nonTerminalModels = this.models.filter(model => {
            return !model.terminal();
        });

        if (nonTerminalModels.length > 0 && !BATCH_FETCH_STATE) {
            // Allow models to fetch their own details.
            var updateFunctions = nonTerminalModels.map(summary => {
                return () => {
                    return summary.fetch();
                };
            });

            return new AJAX_QUEUE.AjaxQueue(updateFunctions).done(_delayThenMonitorAgain);
        } else if (nonTerminalModels.length > 0) {
            // Batch fetch updated state...
            this.fetch({ remove: false }).done(_delayThenMonitorAgain);
        } else {
            _delayThenMonitorAgain();
        }
    },

    /** clear the timeout and the cached timeout id */
    clearUpdateTimeout: function() {
        if (this.updateTimeoutId) {
            clearTimeout(this.updateTimeoutId);
            this.updateTimeoutId = null;
        }
    },

    toString: function() {
        return `JobStatesSummaryCollection()`;
    }
});
示例#6
0
            // routing matures.
            console.warn(
                "This Galaxy Tour is attempting to use path navigation.  This is known to be unstable and can possibly get the Galaxy client 'stuck' in a tour, and at this time is not allowed."
            );
            delete step.path;
        }
    });
    return data;
};

var TourItem = Backbone.Model.extend({
    urlRoot: `${gxy_root}api/tours`
});

var Tours = Backbone.Collection.extend({
    url: `${gxy_root}api/tours`,
    model: TourItem
});

export var ToursView = Backbone.View.extend({
    title: _l("Tours"),
    initialize: function() {
        var self = this;
        this.setElement("<div/>");
        this.model = new Tours();
        this.model.fetch({
            success: function() {
                self.render();
            },
            error: function() {
                // Do something.
                console.error("Failed to fetch tours.");
示例#7
0
define(function(require) {
  "use strcict";
  
  var Backbone = require('libs/backbone');
  var Weapons = require('battle-engine/Items/Weapons');
  var Armors = require('battle-engine/Items/Armors');
  var Actions = require('battle-engine/Actions/Actions');
  
  var Character = Backbone.Model.extend({
    
    get: function(attr) {                  ////////////// Backbone getter fix
      var value = Backbone.Model.prototype.get.call(this, attr);
        return _.isFunction(value) ? value.call(this) : value;
      },
   
    defaults: {
      wait: 100,
      weapon: "",
      armor: "",
      actions: []
    },
    
    initialize: function(model){
      //////////////////    Subattributes
      
      var self = this;

      this.set({
        
        maxHp: function (){
          return this.get("strength") * 3;
        },
        
        initiative: function (){
         return  this.get("agility") * 3;
        },
        
        offense: function (){
         return this.get("strength") * 5;
        },
        
        defense: function (){
          return this.get("strength") + this.get("agility") * 3;
        }
      });
      
      if(this.get("hp") == undefined){
        this.set({
          hp: this.get("maxHp")
        })
      };
      
      //////////////////       Turn
      
      /*this.on("change:wait", function(character){
        if (character.get("wait")<= 0)
          alert(character.get("name") + " is ready for action!");
      })*/
      
      //////////////////      Death
      this.on("change:hp", function(character){
        if(character.get("hp") <= 0){
          console.log(character.get("name") + " has fainted!");
					$.snackbar({content: character.get("name") + " has fainted!"});
          character.set({wait: Infinity});
        }
      });
     
    }
    
  });
  
  var CharacterList = Backbone.Collection.extend({
    model: Character,  
    
    clone: function(deep) {            ///////// Backbone deep cloning fix
      if(deep) {
        return new this.constructor(_.map(this.models, function(m) { return m.clone(); }));
      }else{
        return Backbone.Collection.prototype.clone();
      }
    },
    initialize: function(model){   

    }
  });
  
  function Characters(){
    this.defaultCharacterList = new CharacterList();
    this.characterList = new CharacterList();
    
    this.contAllies = function (){
      return this.characterList.where({faction:"ally"}).length;
    }
    this.contEnemies = function (){
      return this.characterList.where({faction:"enemy"}).length;
    }
  };
    
  Characters.prototype.load = function(file, Bview){
    var filereader = new FileReader();
    var self = this;
    
    filereader.onloadend = function (){
      self.defaultCharacterList = new CharacterList(JSON.parse(filereader.result));
      self.characterList = self.defaultCharacterList.clone(true);
      if(Bview != undefined)
        for (var i = 0; i < self.characterList.length; i++)
          new Bview({model: self.characterList.at(i)});
      
    }
    filereader.readAsText(file,'utf8');
  };
  
  Characters.prototype.newCharacter = function(data){
    var character = new Character(data);
    character.set({id:character.get("name")});
    this.defaultCharacterList.add(character);
    this.characterList.add(character.clone());
    return this.characterList.get(character.get("name"));
  };
	
  Characters.prototype.newCharacterFromArray = function(data){
	  for(i = 0; i < data.length; i++){
	  	this.newCharacter(data[i]);
	  };
  };
  
  Characters.prototype.reset = function(){
    this.characterList.set(this.defaultCharacterList.models);
  };
  
  Characters.prototype.deadFaction = function(){
    if (this.characterList.where({faction:"ally", hp: 0}).length == this.contAllies() || 
        this.characterList.where({faction:"enemy", hp: 0}).length == this.contEnemies())
      return true;
    return false;
  }
  
  Characters.prototype.turn = function(){
    for (var i = 0; i < this.characterList.length; i++){
      var newWait = this.characterList.at(i).get("wait") - this.characterList.at(i).get("initiative");
      if (newWait < 0) newWait = 0;
      this.characterList.at(i).set({wait:newWait});
    }
  };
  
  Characters.prototype.stringify = function(){
    return JSON.stringify(this.characterList);
  };
  
  Characters.prototype.change = function(attr, exp){
    var finalExp = this.parse(attr, exp);
    if (finalExp == undefined) return;
    
    for (var i = 0; i < this.characterList.length; i++){
      this.characterList.at(i).set(attr, eval(finalExp));
    }
  };
  
  
  Characters.prototype.parse = function(attr,expression){
    attr = attr.toString();
    expression = expression.toString();
    
    if (attr.match(/^\w+strength$|^\w+agility$|^\w+intelligence$/i) && 
        expression.match(/^\d*$/)){
      return expression;
    }

    var exp = "";
    if(/(strength|agility|intelligence)/i.exec(expression))
      exp = expression.replace(
          /(strength|agility|intelligence|hp|maxHp|initiative|offense|defense)/ig, 
          'this.get(\"'+ "$&" + '\")');
    
   return "(function(){return " + exp + "})";
    
  };
  
  Characters.prototype.arrayToCollection = function(arr){ //Characters without view
    var chars = [];
    for(var i = 0; i < arr.length; i++)
      chars.push(new CharacterList(arr[i]));
    return chars;
  };
	
	Characters.prototype.infoWait = function() {
		var str = "\n";
		this.characterList.each( function(character) {
			str += character.get("name") + ": \t" + character.get("wait") + '\n';
		});
		return str;
	};
	
	Characters.prototype.waitCheck = function() {
		return (this.characterList.where({wait: 0}).length > 0)
	};
	
	Characters.prototype.getCharacter = function(condition) {
		return this.characterList.where(condition)[0];
	};
  
  return Characters;
});
var ControlledFetchCollection = Backbone.Collection.extend({
    /** call setOrder on initialization to build the comparator based on options */
    initialize: function(models, options) {
        Backbone.Collection.prototype.initialize.call(this, models, options);
        this.setOrder(options.order || this.order, { silent: true });
    },

    /** set up to track order changes and re-sort when changed */
    _setUpListeners: function() {
        return this.on({
            "changed-order": this.sort
        });
    },

    /** override to provide order and offsets based on instance vars, set limit if passed,
     *  and set allFetched/fire 'all-fetched' when xhr returns
     */
    fetch: function(options) {
        options = this._buildFetchOptions(options);
        Galaxy.debug("fetch options:", options);
        return Backbone.Collection.prototype.fetch.call(this, options);
    },

    /** build ajax data/parameters from options */
    _buildFetchOptions: function(options) {
        // note: we normally want options passed in to override the defaults built here
        // so most of these fns will generate defaults
        options = _.clone(options) || {};

        // jquery ajax option; allows multiple q/qv for filters (instead of 'q[]')
        options.traditional = true;

        // options.data
        // we keep limit, offset, etc. in options *as well as move it into data* because:
        // - it makes fetch calling convenient to add it to a single options map (instead of as mult. args)
        // - it allows the std. event handlers (for fetch, etc.) to have access
        //   to the pagination options too
        //      (i.e. this.on( 'sync', function( options ){ if( options.limit ){ ... } }))
        // however, when we send to xhr/jquery we copy them to data also so that they become API query params
        options.data = options.data || this._buildFetchData(options);
        Galaxy.debug("data:", options.data);

        // options.data.filters --> options.data.q, options.data.qv
        var filters = this._buildFetchFilters(options);
        Galaxy.debug("filters:", filters);
        if (!_.isEmpty(filters)) {
            _.extend(options.data, this._fetchFiltersToAjaxData(filters));
        }
        Galaxy.debug("data:", options.data);
        return options;
    },

    /** Build the dictionary to send to fetch's XHR as data */
    _buildFetchData: function(options) {
        var defaults = {};
        if (this.order) {
            defaults.order = this.order;
        }
        return _.defaults(_.pick(options, this._fetchParams), defaults);
    },

    /** These attribute keys are valid params to fetch/API-index */
    _fetchParams: [
        /** model dependent string to control the order of models returned */
        "order",
        /** limit the number of models returned from a fetch */
        "limit",
        /** skip this number of models when fetching */
        "offset",
        /** what series of attributes to return (model dependent) */
        "view",
        /** individual keys to return for the models (see api/histories.index) */
        "keys"
    ],

    /** add any needed filters here based on collection state */
    _buildFetchFilters: function(options) {
        // override
        return _.clone(options.filters || {});
    },

    /** Convert dictionary filters to qqv style arrays */
    _fetchFiltersToAjaxData: function(filters) {
        // return as a map so ajax.data can extend from it
        var filterMap = {
            q: [],
            qv: []
        };
        _.each(filters, (v, k) => {
            // don't send if filter value is empty
            if (v === undefined || v === "") {
                return;
            }
            // json to python
            if (v === true) {
                v = "True";
            }
            if (v === false) {
                v = "False";
            }
            if (v === null) {
                v = "None";
            }
            // map to k/v arrays (q/qv)
            filterMap.q.push(k);
            filterMap.qv.push(v);
        });
        return filterMap;
    },

    /** override to reset allFetched flag to false */
    reset: function(models, options) {
        this.allFetched = false;
        return Backbone.Collection.prototype.reset.call(this, models, options);
    },

    // ........................................................................ order
    order: null,

    /** @type {Object} map of collection available sorting orders containing comparator fns */
    comparators: {
        update_time: BASE_MVC.buildComparator("update_time", {
            ascending: false
        }),
        "update_time-asc": BASE_MVC.buildComparator("update_time", {
            ascending: true
        }),
        create_time: BASE_MVC.buildComparator("create_time", {
            ascending: false
        }),
        "create_time-asc": BASE_MVC.buildComparator("create_time", {
            ascending: true
        })
    },

    /** set the order and comparator for this collection then sort with the new order
     *  @event 'changed-order' passed the new order and the collection
     */
    setOrder: function(order, options) {
        options = options || {};
        var collection = this;
        var comparator = collection.comparators[order];
        if (_.isUndefined(comparator)) {
            throw new Error(`unknown order: ${order}`);
        }
        // if( _.isUndefined( comparator ) ){ return; }
        if (comparator === collection.comparator) {
            return;
        }

        collection.order = order;
        collection.comparator = comparator;

        if (!options.silent) {
            collection.trigger("changed-order", options);
        }
        return collection;
    }
});