define(function(require, exports, module) {
    var Backbone = require('Backbone'),
        Project  = require('models/Project');

    module.exports = Backbone.Collection.extend({
        model: Project
    });

});
Example #2
0
    function initColumn(options, metadata, fieldChoiceOptions) {
        var $editor, $fieldChoice, collection, util, template, sortingLabels;

        $editor = $(options.form);
        $fieldChoice = $editor.find('[data-purpose=column-selector]');
        $fieldChoice.fieldChoice(_.extend({}, fieldChoiceOptions, {select2: {}}));

        $editor.find('[data-purpose=function-selector]').functionChoice({
            converters: metadata.converters,
            aggregates: metadata.aggregates
        });

        collection = new (Backbone.Collection)(load('columns'), {model: ColumnModel});
        collection.on('add remove sort change', function () {
            save(collection.toJSON(), 'columns');
        });

        $editor.itemsManagerEditor($.extend(options.editor, {
            collection: collection,
            setter: function ($el, name, value) {
                if (name === 'func') {
                    value = value.name;
                }
                return value;
            },
            getter: function ($el, name, value) {
                if (name === 'func') {
                    value = value && {
                        name: value,
                        group_type: $el.find(":selected").data('group_type'),
                        group_name: $el.find(":selected").data('group_name')
                    };
                }
                return value;
            }
        }));

        sortingLabels = {};
        $editor.find('select[name*=sorting]').find('option:not([value=""])').each(function () {
            sortingLabels[this.value] = $(this).text();
        });

        util = $fieldChoice.data('oroentity-fieldChoice').entityFieldUtil;
        template = _.template(fieldChoiceOptions.select2.formatSelectionTemplate);

        $(options.itemContainer).itemsManagerTable({
            collection: collection,
            itemTemplate: $(options.itemTemplate).html(),
            itemRender: function (tmpl, data) {
                var item, itemFunc,
                    func = data.func,
                    name = util.splitFieldId(data.name);

                data.name = template(name);
                if (func && func.name) {
                    item = metadata[func.group_type][func.group_name];
                    if (item) {
                        itemFunc = _.findWhere(item.functions, {name: func.name});
                        if (itemFunc) {
                            data.func = itemFunc.label;
                        }
                    }
                } else {
                    data.func = '';
                }
                if (data.sorting && sortingLabels[data.sorting]) {
                    data.sorting = sortingLabels[data.sorting];
                }

                return tmpl(data);
            },
            deleteHandler: _.bind(deleteHandler, null, collection)
        });
    }
Example #3
0
	},

	render() {
		// Clear out this element.
		this.$el.empty();

		this.collection.each(function(model) {
			var view = new UserView({model: model});
			this.$el.append(view.render().el);
		}, this);

		return this;
	}
});

let UserList = Backbone.Collection.extend({ model: UserModel });
let userList = new UserList();

let userListView = new UserListView({
	collection: userList,
	el: '#users'
});

function initLoading() {
	console.log('initLoading');
	$.get('http://rating.smartjs.academy/rating').then((data) => {
		userList.add(data.records);
		console.log('init version — ', data.version);
	});
}
Example #4
0
/* jshint -W097 */
"use strict";

var Backbone = require('backbone');
var Tournament = require('./tournament');
var messageBus = require('../common/router/messageBus');

var TournamentCollection = Backbone.Collection.extend({
  url: "tournaments",
  model: Tournament
});

messageBus.reply('tournaments:tail', function (num) {
  var tournaments = new TournamentCollection();
  tournaments.fetch({data: {offset: 0, limit: num || 10, sort: 'date', order: 'desc'}, reset: true});
  return tournaments;
});

module.exports = TournamentCollection;
Example #5
0
const Store = Bb.Collection.extend({
    initialize() {
        this.id = 1;
        this.selectedId = null;
    },
    getSelected() {
        if(this.selectedId) return this.get(this.selectedId);
    },
    buildData(count = 1000) {
        var adjectives = ["pretty", "large", "big", "small", "tall", "short", "long", "handsome", "plain", "quaint", "clean", "elegant", "easy", "angry", "crazy", "helpful", "mushy", "odd", "unsightly", "adorable", "important", "inexpensive", "cheap", "expensive", "fancy"];
        var colours = ["red", "yellow", "blue", "green", "pink", "brown", "purple", "brown", "white", "black", "orange"];
        var nouns = ["table", "chair", "house", "bbq", "desk", "car", "pony", "cookie", "sandwich", "burger", "pizza", "mouse", "keyboard"];
        var data = [];
        for (var i = 0; i < count; i++)
            data.push({id: this.id++, label: adjectives[_random(adjectives.length)] + " " + colours[_random(colours.length)] + " " + nouns[_random(nouns.length)] });
        return data;
    },
    updateData(mod = 10) {
        startMeasure("update");
        for (let i=0;i<this.models.length;i+=10) {
            const label = this.models[i].get('label');
            this.models[i].set('label', label + ' !!!');
        }
        stopMeasure();
    },
    delete(id, view) {
        startMeasure("delete");
        view.removeRow(id);
        this.remove(id, { silent: true });
        stopMeasure();
    },
    run() {
        startMeasure("run");
        if(this.model.length) this._clear();
        this.reset(this.buildData());
        stopMeasure();
    },
    addData() {
        startMeasure("add");
        this.add(this.buildData(1000));
        stopMeasure();
    },
    select(id, view) {
        startMeasure("select");
        view.setSelected(id);
        this.selectedId = id;
        stopMeasure();
    },
    runLots() {
        startMeasure("runLots");
        if(this.model.length) this._clear();
        this.reset(this.buildData(10000));
        stopMeasure();
    },
    _clear() {
        _.each(this.models, model => model.off());
        this._reset();
    },
    clear() {
        startMeasure("clear");
        this._clear();
        this.trigger('reset', this);
        stopMeasure();
    },
    swapRows() {
        startMeasure("swapRows");
        if (this.length > 998) {
            const a = this.models[1];
            this.models[1] = this.models[998];
            this.models[998] = a;
            this.trigger('swap', this.models[1], this.models[998]);
        }
        stopMeasure();
    }
});
const DiscountCollection = Bb.Collection.extend({
    model: DiscountModel,
    initialize: function(options) {
        this.on('remove', this.channelCall);
        this.on('sync', this.channelCall);
        this.on('reset', this.channelCall);
        this.on('add', this.channelCall);
    },
    channelCall: function(){
        var channel = Radio.channel('facade');
        channel.trigger('changed:discount');
    },
    url: function(){
        return AppOption['context_url'] + '/' + 'discount_lines';
    },
    ht: function(){
        var result = 0;
        this.each(function(model){
            result += model.ht();
        });
        return result;
    },
    tvaParts: function(){
        var result = {};
        this.each(function(model){
            var tva_amount = model.tva();
            var tva = model.get('tva');
            if (tva in result){
                tva_amount += result[tva];
            }
            result[tva] = tva_amount;
        });
        return result;
    },
    ttc: function(){
        var result = 0;
        this.each(function(model){
            result += model.ttc();
        });
        return result;
    },
    insert_percent: function(model){
        /*
         * Call the server to generate percent based Discounts
         * :param obj model: A DiscountPercentModel instance
         */
        var serverRequest = ajax_call(
            this.url() + '?action=insert_percent',
            model.toJSON(),
            'POST'
        );
        serverRequest.then(this.fetch.bind(this));
    },
    validate: function(){
        var result = {};
        this.each(function(model){
            var res = model.validate();
            if (res){
                _.extend(result, res);
            }
        });
        return result;
    }
});
App.module('Models', function(models) {
    models.Accounts = Backbone.Collection.extend({
        model: models.Account
    });
});
Example #8
0
var Structure = Backbone.Collection.extend({
    model: Activity,

    constructor: function () {
        mediator.on('activity:start', this.onPageChange, this);
        Backbone.Collection.apply(this, arguments);
    },

    onPageChange: function (page) {
        var item = this.find(function (model) {
            return model.get('cid') === page.get('cid');
        });

        this.invoke('set', {
            'active': false,
            'here': false
        }, {
            silent: true
        });


        if (item) {
            var models = item.getPatch();

            _.invoke(models, 'set', {
                'active': true
            });

            item.set('here', true);
            this.trigger('changed');
        }
    },

    getCurrent: function () {
        var current = this.findWhere({
            'here': true
        });

        return current;
    },

    findModelByCid: function (cid) {
        return this.find(function (model) {
            return model.cid === cid;
        });
    }

});
// fetch method, returns es6 promises
// if you uncomment 'universal-utils' below, you can comment out this line
import fetch from "isomorphic-fetch"


import $ from "jquery";
import _ from "underscore";
import Backbone from "backbone";


import DOM from 'react-dom'
import React, {Component} from 'react'

var ProductModel = Backbone.Model

var ProductCollection = Backbone.Collection.extend({
})

var EtsyCollection = Backbone.Collection.extend({
  accessToken: 'rtf0g2lb2o0xqsksl3jcro8z',

  url: function(){
    return "https://openapi.etsy.com/v2/listings/active.js?includes=Images&callback=?&api_key="+this.accessToken
  },

  parse: function(payload){
    return payload.results
  }
})


Example #10
0
var $ = require("jquery"),
  _ = require("underscore"),
  Backbone = require("backbone"),
  config = require("../config");


  module.exports = Backbone.Collection.extend({
      url: function () {
          return config.apiHost + "/ranks";
      },
      parse: function (response, options) {
          return response.ranks || [];
      }
  });
define(function (require) {
    var ep = require('ep');
    var EventBus = require('eventbus');
    var Mediator = require('mediator');
    var Backbone = require('backbone');
    var pace = require('pace');
    var i18n = require('i18n');

    var Model = require('checkout.models');
    var View = require('checkout.views');
    var template = require('text!modules/base/checkout/base.checkout.templates.html');

    $('#TemplateContainer').append(template);
    _.templateSettings.variable = 'E';


    var checkoutModel = new Model.CheckoutModel();
    var checkoutSummaryModel = new Model.CheckoutSummaryModel();
    var billingAddressCollection = new Backbone.Collection();
    var shippingAddressCollection = new Backbone.Collection();
    var shippingOptionsCollection = new Model.CheckoutShippingOptionsCollection();
    var paymentMethodCollection = new Model.CheckoutPaymentMethodsCollection();

    var checkoutLayout = new View.DefaultLayout();


    /**
     * Controller logic to render billing address views in designated region
     * @param region  region to render the view into
     */
    var showBillingAddressesView = function(region) {
      var profileBillingAddressesView =  new View.BillingAddressesCompositeView({
        collection: billingAddressCollection
      });

      region.show(profileBillingAddressesView);
    };

    /**
     * Controller logic to render shipping address views in designated region (and calls showShippingOptionView function
     * to render shipping option views into shippingOptionsRegion
     * @param region  region to render the view into
     */
    var showShippingAddressesView = function(region) {
      var profileShippingAddressesView = new View.ShippingAddressesCompositeView({
        collection: shippingAddressCollection
      });

      // Only populate the shipping options region if there is at least one shipping address
      if (shippingAddressCollection.length > 0) {
        setAsChosen('shippingOptions', 'checkout.updateChosenShippingOptionRequest');
        shippingOptionsCollection.update(checkoutModel.get('shippingOptions'));
        showSippingOptionsView(checkoutLayout.shippingOptionsRegion);
      }

      region.show(profileShippingAddressesView);
    };

    /**
     * Controller logic to render shipping option views in designated region
     * @param region  region to render the view into
     */
    var showSippingOptionsView = function(region) {
      var profileShippingOptionsView = new View.ShippingOptionsCompositeView({
        collection: shippingOptionsCollection
      });
      region.show(profileShippingOptionsView);
    };

    /**
     * Controller logic to render payment method views in designated region
     * @param region  region to render the view into
     */
    var showPaymentMethodsView = function (region) {
      var profilePaymentMethodsView = new View.PaymentMethodsCompositeView({
        collection: paymentMethodCollection
      });
      region.show(profilePaymentMethodsView);
    };

    /**
     * Controller logic to render checkout summary views in designated region
     * @param region  region to render the summary view into
     */
    var showCheckoutSummaryView = function (region) {
      var checkoutSummaryView = new View.CheckoutSummaryView({
        model: checkoutSummaryModel
      });

      checkoutSummaryView.on('show', function() {
        // Only show taxes summary if tax amount is greater than zero
        var taxes = checkoutSummaryModel.get('taxes');
        if ( taxes && taxes.length && taxes[0].amount > 0 ) {
          checkoutSummaryView.checkoutTaxTotalRegion.show(
            new View.CheckoutTaxTotalView({
              model: new Backbone.Model(checkoutSummaryModel.get('taxTotal'))
            })
          );
          checkoutSummaryView.checkoutTaxBreakDownRegion.show(
            new View.CheckoutTaxesCollectionView({
              collection: new Backbone.Collection(taxes)
            })
          );
        }
        // If there are shipping costs, show them in the checkout summary
        var shippingTotal = checkoutSummaryModel.get('shippingTotal');
        if (shippingTotal) {
          checkoutSummaryView.checkoutShippingTotalRegion.show(
            new View.CheckoutShippingTotalView({
              model: new Backbone.Model(shippingTotal)
            })
          );
        }
      });

      region.show(checkoutSummaryView);
    };


    /**
     * Instantiate an checkout DefaultLayout and load views into corresponding regions
     * @returns {View.DefaultLayout}  fully rendered checkout DefaultLayout
     */
    var defaultController = function () {
      var orderLink = getOrderLink();

      checkoutModel.fetch({
        url: checkoutModel.getUrl(orderLink),
        success: function (response) {
          checkoutLayout.checkoutTitleRegion.show(new View.CheckoutTitleView());

          setAsChosen('billingAddresses', 'checkout.updateChosenBillingAddressRequest');
          billingAddressCollection.update(checkoutModel.get('billingAddresses'));
          showBillingAddressesView(checkoutLayout.billingAddressesRegion);

          // Only show if the cart contains physical items requiring shipment
          if (checkoutModel.get('deliveryType') === "SHIPMENT") {
            setAsChosen('shippingAddresses', 'checkout.updateChosenShippingAddressRequest');
            shippingAddressCollection.update(checkoutModel.get('shippingAddresses'));
            // shipping Options views' rendering logic is included inside showShippingAddressView
            // as shipping options view will change when shipping address changes
            showShippingAddressesView(checkoutLayout.shippingAddressesRegion);
          }

          setAsChosen('paymentMethods', 'checkout.updateChosenPaymentMethodRequest');
          if (checkoutModel.get('showPaymentMethods')) {
            paymentMethodCollection.update(response.get('paymentMethods'));
            showPaymentMethodsView(checkoutLayout.paymentMethodsRegion);
          }

          checkoutSummaryModel.clear();
          checkoutSummaryModel.set(response.get('summary'));
          showCheckoutSummaryView(checkoutLayout.checkoutOrderRegion);
        }
      });

      return checkoutLayout;
    };

    /**
     * If the model suggests we need to set a chosen (billing/ shipping address, or shipping option),
     * trigger a call to Cortex to formerly set it to display correct summary information
     * @param arrayName name of array of the selectors
     * @param eventName name of event to update chosen selection.
     */
    function setAsChosen (arrayName, eventName) {
      if (checkoutModel.get(arrayName).length && checkoutModel.get(arrayName)[0].setAsDefaultChoice) {
        EventBus.trigger(
          eventName,
          checkoutModel.get(arrayName)[0].selectAction
        );
      }
    }

    /**
     * Get a order link for model fetch url, or trigger checkout access error event
     * @returns String order link (href to access order resource on server)
     */
    function getOrderLink () {
      // Attempt to retrieve an order link from session storage (set by the checkout module)
      var orderLink = ep.io.sessionStore.getItem('orderLink');

      // Trigger an error if we are unable to retrieve a Cortex order link
      if (!orderLink) {
        EventBus.trigger('checkout.checkoutAccessError');
      }

      return orderLink;
    }


    /* ********** SUBMIT ORDER EVENT LISTENERS ************ */
    /**
     * Submit order to cortex.
     * @param submitOrderLink action-link to submit order to.
     */
    function submitOrder(submitOrderLink) {
      if (!submitOrderLink) {
        // FIXME [CU-92] user feedback??
        ep.logger.warn('checkout.submitOrderRequest called with no submitOrderLink');
        return;
      }

      var ajaxModel = new ep.io.defaultAjaxModel({
        type: 'POST',
        url: submitOrderLink,
        success: function (data, textStatus, XHR) {
          // Remove order link data from sessionStorage
          ep.io.sessionStore.removeItem('orderLink');

          var obj = {
            data: data,
            textStatus: textStatus,
            XHR: XHR
          };
          EventBus.trigger('checkout.submitOrderSuccess', obj);
        },
        customErrorFn: function (response) {
          EventBus.trigger('checkout.submitOrderFailed', response);
        }
      });

      ep.io.ajax(ajaxModel.toJSON());
    }

    /**
     * Fire mediator event to handle subsequent actions.
     * @param response  submit order success response
     */
    function submitOrderSuccess(response) {

      var orderSummaryLink = response.XHR.getResponseHeader('Location');
      if (orderSummaryLink) {
        Mediator.fire('mediator.orderProcessSuccess', orderSummaryLink);
        pace.stop();
      }
    }

    /**
     * Listening to submit order button clicked signal,
     * will trigger event to submit order to cortex
     */
    EventBus.on('checkout.submitOrderBtnClicked', function (submitOrderActionLink) {
      ep.ui.disableButton(checkoutLayout.checkoutOrderRegion.currentView, 'submitOrderButton');

      // if cortex says it's ok
      if (submitOrderActionLink) {
        EventBus.trigger('checkout.submitOrderRequest', submitOrderActionLink);
      }
    });

    /**
     * Listening to submit order request,
     * will submit purchase order to cortex.
     */
    EventBus.on('checkout.submitOrderRequest', submitOrder);

    /**
     * Listening to submit order success signal,
     * will fire mediator event to handle subsequent actions.
     */
    EventBus.on('checkout.submitOrderSuccess', submitOrderSuccess);

    /**
     * Listening to submit order failed signal,
     * will show a toast error message and refresh the entire page.
     */
    EventBus.on('checkout.submitOrderFailed', function(response) {
      $().toastmessage('showToast', {
        text: i18n.t('checkout.submitOrderError'),
        sticky: true,
        position: 'middle-center',
        type: 'error',
        close: function() {
          Backbone.history.loadUrl();
        }
      });
    });

    /**
     * Listening to the event fired when we are unable to load the order data.
     * Routes the user to the cart.
     */
    EventBus.on('checkout.checkoutAccessError', function() {
      ep.logger.error('unable to load checkout - missing order link data');
      ep.router.navigate(ep.app.config.routes.cart, true);
    });

    /* ********** CHOOSE BILLING ADDRESS EVENT LISTENERS ************ */
    function displayStickyErrMsg (sectionName) {
      // Display sticky error message
      $().toastmessage('showToast', {
        text: i18n.t('checkout.updateChosenErrMsg.' + sectionName),
        sticky: true,
        position: 'middle-center',
        type: 'error'
      });
    }

    /**
     * Make a ajax POST request to cortex server with given action links, and trigger corresponding events
     * in case of success or error. Start activity indicator in affected regions.
     *
     * @param actionLink url to post request to server with.
     */
    function updateChosenBillingAddress(actionLink) {
      if (actionLink) {
        var ajaxModel = new ep.io.defaultAjaxModel({
          type: 'POST',
          url: actionLink,
          success: function() {
            EventBus.trigger('checkout.updateChosenBillingAddressSuccess');
          },
          customErrorFn: function() {
            EventBus.trigger('checkout.updateChosenBillingAddressFail');
          }
        });

        ep.io.ajax(ajaxModel.toJSON());

        ep.ui.startActivityIndicator(checkoutLayout.billingAddressesRegion.currentView);
        ep.ui.startActivityIndicator(checkoutLayout.checkoutOrderRegion.currentView);
      }
      else {
        ep.logger.error("Trying to update chosen billing address without action link");
      }
    }


    /**
     * Refresh views affected by changing billing address selector with data from Cortex.
     * Removes activity indicator on reload success.
     */
    function refreshBillingAddressViews() {
      var orderLink = getOrderLink();

      checkoutModel.fetch({
        url: checkoutModel.getUrl(orderLink),
        success: function(response) {
          billingAddressCollection.update(response.get('billingAddresses'));
          showBillingAddressesView(checkoutLayout.billingAddressesRegion);

          checkoutSummaryModel.clear();
          checkoutSummaryModel.set(response.get('summary'));
          showCheckoutSummaryView(checkoutLayout.checkoutOrderRegion);

          ep.ui.stopActivityIndicator(checkoutLayout.billingAddressesRegion.currentView);
          ep.ui.stopActivityIndicator(checkoutLayout.checkoutOrderRegion.currentView);
        }
      });
    }

    /**
     * In case of billing address selection update failure, will notify user with toastmessage error, and reload regions
     * with date from Cortex server.
     */
    function updateChosenBillingAddressFailed() {
      displayStickyErrMsg('billingAddress');
      refreshBillingAddressViews();
    }

    /**
     * Handler for the checkout.billingAddressRadioChanged event.
     */
    EventBus.on('checkout.billingAddressRadioChanged', function(actionLink) {
      EventBus.trigger('checkout.updateChosenBillingAddressRequest', actionLink);
    });

    /**
     * Listening to request to update the chosen billing address. Will request to the Cortex server.
     */
    EventBus.on('checkout.updateChosenBillingAddressRequest', updateChosenBillingAddress);

    /**
     * Listening to the event fired on successful update of the chosen billing address.
     * Reload regions so display in in-sync with server
     */
    EventBus.on('checkout.updateChosenBillingAddressSuccess', refreshBillingAddressViews);

    /**
     * Listening to the event fired when the update of a chosen billing address fails.
     * Displays a toast error message, and reload regions so display in in-sync with server.
     */
    EventBus.on('checkout.updateChosenBillingAddressFail', updateChosenBillingAddressFailed);


    /* ********** CHOOSE SHIPPING ADDRESS EVENT LISTENERS ************ */
    /**
     * Make a ajax POST request to cortex server with given action links, and trigger corresponding events
     * in case of success or error. Start activity indicator in affected regions.
     *
     * @param actionLink url to post request to server with.
     */
    function updateChosenShippingAddress(actionLink) {
      if (actionLink) {
        var ajaxModel = new ep.io.defaultAjaxModel({
          type: 'POST',
          url: actionLink,
          success: function() {
            EventBus.trigger('checkout.updateChosenShippingAddressSuccess');
          },
          customErrorFn: function() {
            EventBus.trigger('checkout.updateChosenShippingAddressFail');
          }
        });

        ep.io.ajax(ajaxModel.toJSON());

        ep.ui.startActivityIndicator(checkoutLayout.shippingAddressesRegion.currentView);
        ep.ui.startActivityIndicator(checkoutLayout.shippingOptionsRegion.currentView);
        ep.ui.startActivityIndicator(checkoutLayout.checkoutOrderRegion.currentView);
      }
      else {
        ep.logger.error("Trying to update chosen shipping address without action link");
      }
    }


    /**
     * Refresh views affected by changing shipping address selector with data from Cortex.
     * Removes activity indicator on reload success.
     */
    function refreshShippingAddressViews() {
      var orderLink = getOrderLink();

      checkoutModel.fetch({
        url: checkoutModel.getUrl(orderLink),
        success: function(response) {
          shippingAddressCollection.update(checkoutModel.get('shippingAddresses'));
          showShippingAddressesView(checkoutLayout.shippingAddressesRegion);

          checkoutSummaryModel.clear();
          checkoutSummaryModel.set(response.get('summary'));
          showCheckoutSummaryView(checkoutLayout.checkoutOrderRegion);

          ep.ui.stopActivityIndicator(checkoutLayout.shippingAddressesRegion.currentView);
          ep.ui.stopActivityIndicator(checkoutLayout.shippingOptionsRegion.currentView);
          ep.ui.stopActivityIndicator(checkoutLayout.checkoutOrderRegion.currentView);
        }
      });
    }

    /* ********** SHIPPING OPTION EVENT LISTENERS ************ */
    /**
     * In case of shipping address selection update failure, will notify user with toastmessage error, and reload regions
     * with date from Cortex server.
     */
    function updateChosenShippingAddressFailed() {
      displayStickyErrMsg('shippingAddress');
      refreshShippingAddressViews();
    }

    /**
     * Handler for the checkout.shippingAddressRadioChanged event.
     */
    EventBus.on('checkout.shippingAddressRadioChanged', function(actionLink) {
      EventBus.trigger('checkout.updateChosenShippingAddressRequest', actionLink);
    });

    /**
     * Listening to request to update the chosen shipping address. Will request to the Cortex server.
     */
    EventBus.on('checkout.updateChosenShippingAddressRequest', updateChosenShippingAddress);

    /**
     * Listening to the event fired on successful update of the chosen shipping address.
     * Reload regions so display in in-sync with server
     */
    EventBus.on('checkout.updateChosenShippingAddressSuccess', refreshShippingAddressViews);

    /**
     * Listening to the event fired when the update of a chosen shipping address fails.
     * Displays a toast error message, and reload regions so display in in-sync with server.
     */
    EventBus.on('checkout.updateChosenShippingAddressFail', updateChosenShippingAddressFailed);


    /* ********** CHOOSE SHIPPING OPTION EVENT LISTENERS ************ */
    /**
     * Make a ajax POST request to cortex server with given action links, and trigger corresponding events
     * in case of success or error. Start activity indicator in affected regions.
     *
     * @param actionLink url to post request to server with.
     */
    function updateChosenShippingOption(actionLink) {
      if (actionLink) {
        var ajaxModel = new ep.io.defaultAjaxModel({
          type: 'POST',
          url: actionLink,
          success: function() {
            EventBus.trigger('checkout.updateChosenShippingOptionSuccess');
          },
          customErrorFn: function() {
            EventBus.trigger('checkout.updateChosenShippingOptionFailed');
          }
        });

        ep.io.ajax(ajaxModel.toJSON());

        refreshShippingAddressViews();
        ep.ui.startActivityIndicator(checkoutLayout.shippingOptionsRegion.currentView);
        ep.ui.startActivityIndicator(checkoutLayout.checkoutOrderRegion.currentView);
      }
      else {
        ep.logger.error("Trying to update chosen shipping option without action link");
      }
    }


    /**
     * Refresh views affected by changing shipping option selector with data from Cortex.
     * Removes activity indicator on reload success.
     */
    function refreshShippingOptionViews() {
      var orderLink = getOrderLink();

      checkoutModel.fetch({
        url: checkoutModel.getUrl(orderLink),
        success: function(response) {
          shippingOptionsCollection.update(response.get('shippingOptions'));
          showSippingOptionsView(checkoutLayout.shippingOptionsRegion);

          checkoutSummaryModel.clear();
          checkoutSummaryModel.set(response.get('summary'));
          showCheckoutSummaryView(checkoutLayout.checkoutOrderRegion);

          ep.ui.stopActivityIndicator(checkoutLayout.shippingOptionsRegion.currentView);
          ep.ui.stopActivityIndicator(checkoutLayout.checkoutOrderRegion.currentView);
        }
      });
    }

    /**
     * In case of shipping option selection update failure, will notify user with toastmessage error, and reload regions
     * with date from Cortex server.
     */
    function updateChosenShippingOptionFailed() {
      displayStickyErrMsg('shippingOption');
      refreshShippingOptionViews();
    }

    /**
     * Handler for the checkout.shippingOptionRadioChanged event.
     */
    EventBus.on('checkout.shippingOptionRadioChanged', function(actionLink) {
      EventBus.trigger('checkout.updateChosenShippingOptionRequest', actionLink);
    });

    /**
     * Listening to request to update the chosen shipping option. Will request to the Cortex server.
     */
    EventBus.on('checkout.updateChosenShippingOptionRequest', updateChosenShippingOption);

    /**
     * Listening to the event fired on successful update of the chosen shipping option.
     * Reload regions so display in in-sync with server
     */
    EventBus.on('checkout.updateChosenShippingOptionSuccess', refreshShippingOptionViews);

    /**
     * Listening to the event fired when the update of a chosen shipping option fails.
     * Displays a toast error message, and reload regions so display in in-sync with server.
     */
    EventBus.on('checkout.updateChosenShippingOptionFailed', updateChosenShippingOptionFailed);


    /* ********** CHOOSE PAYMENT METHOD EVENT LISTENERS ************ */
    /**
     * Make a ajax POST request to cortex server with given action links, and trigger corresponding events
     * in case of success or error. Start activity indicator in affected regions.
     *
     * @param actionLink url to post request to server with.
     */
    function updateChosenPaymentMethod(actionLink) {
      if (actionLink) {
        var ajaxModel = new ep.io.defaultAjaxModel({
          type: 'POST',
          url: actionLink,
          success: function() {
            EventBus.trigger('checkout.updateChosenPaymentMethodSuccess');
          },
          customErrorFn: function() {
            EventBus.trigger('checkout.updateChosenPaymentMethodFailed');
          }
        });

        ep.io.ajax(ajaxModel.toJSON());

        ep.ui.startActivityIndicator(checkoutLayout.paymentMethodsRegion.currentView);
        ep.ui.startActivityIndicator(checkoutLayout.checkoutOrderRegion.currentView);
      }
      else {
        ep.logger.error("Trying to update chosen payment method without action link");
      }
    }

    /**
     * Refresh views affected by changing payment mthod selector with data from Cortex.
     * Removes activity indicator on reload success.
     */
    function refreshPaymentMethodViews() {
      var orderLink = getOrderLink();

      checkoutModel.fetch({
        url: checkoutModel.getUrl(orderLink),
        success: function(response) {
          paymentMethodCollection.update(response.get('paymentMethods'));
          showPaymentMethodsView(checkoutLayout.paymentMethodsRegion);

          checkoutSummaryModel.clear();
          checkoutSummaryModel.set(response.get('summary'));
          showCheckoutSummaryView(checkoutLayout.checkoutOrderRegion);

          ep.ui.stopActivityIndicator(checkoutLayout.paymentMethodsRegion.currentView);
          ep.ui.stopActivityIndicator(checkoutLayout.checkoutOrderRegion.currentView);
        }
      });
    }

    /**
     * In case of payment method selection update failure, will notify user with toastmessage error, and reload regions
     * with date from Cortex server.
     */
    function updateChosenPaymentMethodFailed() {
      displayStickyErrMsg('paymentMethod');
      refreshPaymentMethodViews();
    }

    /**
     * Handler for the checkout.paymentMethodRadioChanged event.
     */
    EventBus.on('checkout.paymentMethodRadioChanged', function(actionLink) {
      EventBus.trigger('checkout.updateChosenPaymentMethodRequest', actionLink);
    });

    /**
     * Listening to request to update the chosen payment method. Will request to the Cortex server.
     */
    EventBus.on('checkout.updateChosenPaymentMethodRequest', updateChosenPaymentMethod);

    /**
     * Listening to the event fired on successful update of the chosen payment method.
     * Reload regions so display in in-sync with server
     */
    EventBus.on('checkout.updateChosenPaymentMethodSuccess', refreshPaymentMethodViews);

    /**
     * Listening to the event fired when the update of a chosen payment method fails.
     * Displays a toast error message, and reload regions so display in in-sync with server.
     */
    EventBus.on('checkout.updateChosenPaymentMethodFailed', updateChosenPaymentMethodFailed);


    /* ********** ADD / DELETE NEW ADDRESS EVENT LISTENERS ************ */
    /**
     * Listen to add new address button clicked signal
     * will load address form
     */
    EventBus.on('checkout.addNewAddressBtnClicked', function () {
      Mediator.fire('mediator.addNewAddressRequest', 'checkout');
    });

    /**
     * Listens to the delete address button clicked signal, fires a mediator strategy to communicate with
     * the address module to render the delete confirmation modal.
     */
    EventBus.on('checkout.deleteAddressBtnClicked', function (href) {
      Mediator.fire('mediator.deleteAddressRequest', {
        href: href,
        indicatorView: checkoutLayout,
        returnModule: 'checkout'
      });
    });

    /**
     * Listens to the edit address button clicked signal, fires a mediator strategy to communicate with
     * the address module to render the edit address form.
     */
    EventBus.on('checkout.editAddressBtnClicked', function (href) {
      Mediator.fire('mediator.editAddressRequest', {
        returnModule: 'checkout',
        href: href
      });
    });

    /**
     * Called when an address has been successfully deleted from Cortex. Performs a fetch of the profile
     * model and updates the collection of addresses with the updated array from Cortex.
     */
    EventBus.on('checkout.updateAddresses', function (indicatorView) {
      ep.ui.stopActivityIndicator(indicatorView);
      /**
       * Many areas of the page need to be updated when an address is deleted, so we perform
       * a full page refresh here instead of opting for a more granular approach
       */
      Backbone.history.loadUrl();
    });

    /* ********** ADD / DELETE NEW PAYMENT EVENT LISTENERS ************ */
    /**
     * Listen to add new payment method button clicked signal
     * will load add new payment method form
     */
    EventBus.on('checkout.addNewPaymentMethodBtnClicked', function () {
      Mediator.fire('mediator.addNewPaymentMethodRequest', 'checkout');
    });

    /**
     * Handler for the delete payment button clicked signal, which triggers a mediator strategy
     * to communicate the request to the payment module.
     */
    EventBus.on('checkout.deletePaymentBtnClicked', function (href) {
      Mediator.fire('mediator.deletePaymentRequest', {
        href: href,
        indicatorView: checkoutLayout.paymentMethodsRegion.currentView,
        returnModule: 'checkout'
      });
    });

    /**
     * Called when an payment method has been successfully deleted from Cortex. Performs a fetch of the profile
     * model and updates the collection of payment methods with the updated array from Cortex.
     */
    EventBus.on('checkout.updatePaymentMethods', function (indicatorView) {
      if (indicatorView) {
        // Stop the activity indicators on the cart regions that are being updated
        ep.ui.stopActivityIndicator(indicatorView);
      }
      ep.ui.startActivityIndicator(checkoutLayout.paymentMethodsRegion.currentView);
      ep.ui.startActivityIndicator(checkoutLayout.checkoutOrderRegion.currentView);

      refreshPaymentMethodViews();
    });

    return {
      DefaultController: defaultController
    };
  }
Example #12
0
var Backbone = require('backbone');

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

var AdUrlUpgradeCollection = Backbone.Collection.extend({
  model: AdUrlUpgrade,
});

module.exports = {
  collection: AdUrlUpgradeCollection,
  model: AdUrlUpgrade
};
Example #13
0
    audible: true,
    authorized: false
  },

  toJSON: function() {
    return {
      id: this.id,
      person: {
        id: this.get('googleId'),
        displayName: this.get('name')
      }
    }
  }
});
var Participants = Backbone.Collection.extend({
  model: Participant
});

var Hangout = Backbone.Model.extend({
  defaults: {
    state: {},
    participants: new Participants(),
    displayedParticipant: null,
    cameraMute: false,
    microphoneMute: false,
    apiReady: true,
    localParticipantVideoMirrored: true,
    localAudioNotificationsMuted: false,
    chatPaneVisible: true
  },
Example #14
0
import Backbone from 'backbone'


export const TodoListModel = Backbone.Model.extend({
	
})

export const TodoListCollection = Backbone.Collection.extend({
	model: TodoListModel
})
Example #15
0
var Backbone = require('backbone');
var Loot = require('../models/loot');

var Loots = module.exports = Backbone.Collection.extend({
  __name__: 'Loots',

  model: Loot
});
Example #16
0
var Collection = Backbone.Collection.extend({
  model: MediaModel,
  baseUrl: 'https://api.instagram.com/v1',
  ajaxOptions: {},

  initialize: function(models, options) {
    _.bindAll(this, 'searchTags', 'url');

    options = options || {};
    this.clientId = options.clientId;
  },

  searchTags: function(tagname, cb) {
    cb = cb || function() {};

    this.tagName = tagname;

    return this.fetch({
      success: function(data) { cb(null, data); },
      error: function(data) { cb(data); }
    });
  },

  searchUsers: function(query, cb) {
    cb = cb || function() {};
  },

  url: function() {
    if(!this.clientId) throw "must give client id when initializing";
    if(!this.tagName) throw "must specify tag before fetching";

    return [ this.baseUrl, 'tags', this.tagName, 'media/recent' ].join('/');
  },

  parse: function(resp) {
    // FIXME: I removed order, sort order is sent from Instagram maybe?
    return resp.data;
  },

  fetch: function(options) {
    options = _.defaults(options || {}, this.ajaxOptions || {});
    options.data = _.extend(options.data || {}, {
      client_id: this.clientId
    });

    addErrorHandling(options);

    return Backbone.Collection.prototype.fetch.call(this, options);
  }
});
Example #17
0
    var actionHandler = actions[action.actionType];
    if (actionHandler) {
      return actionHandler.call(this, action);
    }
  }
});

var collectionStoreUtils = _.extend({}, storeUtils, {
  handleAction: function( action ) {
    var actions, model;

    if (action.id) {
      model = this.get(action.id);
      actions = (model) ? model.actions : {};
      actions = actions || {};
    } else {
      actions = this.actions;
    }
    var actionHandler = actions[action.actionType];
    if (actionHandler) {
      return actionHandler.call(model || this, action);
    }
  }
});

module.exports = {
  Model: backbone.Model.extend(modelStoreUtils),
  Collection: backbone.Collection.extend(collectionStoreUtils),
  backbone: backbone
}
Example #18
0
var WidgetCollection = Backbone.Collection.extend({
    model: WidgetModel,

    /**
     * Get an object containing all of the current parameter values as
     *   modelId -> value
     */
    values: function () {
        var params = {};
        this.each(function (m) {
            // apply special handling for certain parameter types
            // https://github.com/DigitalSlideArchive/slicer/blob/9e5112ab3444ad8c699d70452a5fe4a74ebbc778/server/__init__.py#L44-L46
            switch (m.get('type')) {
                case 'file':
                    params[m.id + '_girderItemId'] = m.value().id;
                    break;
                case 'new-file':
                    params[m.id + '_girderFolderId'] = m.value().get('folderId');
                    params[m.id + '_name'] = m.value().get('name');
                    break;
                case 'image':
                    params[m.id + '_girderFileId'] = m.value().id;
                    break;
                default:
                    params[m.id] = JSON.stringify(m.value());
            }
        });
        return params;
    }
});
Example #19
0
 constructor: function () {
     mediator.on('activity:start', this.onPageChange, this);
     Backbone.Collection.apply(this, arguments);
 },
Example #20
0
module.exports = Backbone.Collection.extend({
  model: Branch,

  initialize: function(models, options) {
    this.repo = options.repo;
  },

  parse: function(resp, options) {
    var gitlab = util.getApiFlavor() === 'gitlab';
    var repo = this.repo;
    return _.map(resp, (function(branch) {
      var commit = branch.commit;
      if (!commit.sha) {
        commit.sha = commit.id;
      }
      return {
        repo: repo,
        name: branch.name,
        commit: commit,
        'protected': gitlab ? branch['protected'] : branch.protection ? branch.protection.enabled : false
      }
    }));
  },

  /*
  fetch: function(options) {
    options = _.clone(options) || {};

    var cb = options.success;

    var success = (function(res, statusText, xhr) {
      this.add(res);
      util.parseLinkHeader(xhr, {
        success: success,
        complete: cb
      });
    }).bind(this);

    Backbone.Collection.prototype.fetch.call(this, _.extend(options, {
      success: (function(model, res, options) {
        util.parseLinkHeader(options.xhr, {
          success: success,
          error: cb
        });
      }).bind(this)
    }));
  },
  */

  url: function() {
    return this.repo.branchesUrl();
  }
});
Example #21
0
    // an animation of 0 is essentially setting the attribute directly
    this.animateToAttr(fromAttr, 0);
    this.animateToAttr(toAttr, speed, easing);
  },

  animateToAttr: function(attr, speed, easing) {
    if (speed === 0) {
      this.get('text').attr(attr.text);
      this.get('rect').attr(attr.rect);
      this.get('arrow').attr(attr.arrow);
      return;
    }

    var s = speed !== undefined ? speed : this.get('animationSpeed');
    var e = easing || this.get('animationEasing');

    this.get('text').stop().animate(attr.text, s, e);
    this.get('rect').stop().animate(attr.rect, s, e);
    this.get('arrow').stop().animate(attr.arrow, s, e);
  }
});

var VisBranchCollection = Backbone.Collection.extend({
  model: VisBranch
});

exports.VisBranchCollection = VisBranchCollection;
exports.VisBranch = VisBranch;
exports.randomHueString = randomHueString;

Example #22
0
module.exports = Backbone.Collection.extend({

  model: function (attrs, opts) {
    var d = {};
    if (typeof attrs === 'string') {
      d.val = attrs;
    } else {
      d = attrs;
    }
    return new CustomListItemModel(d);
  },

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

  _initBinds: function () {
    this.bind('change:selected', this._onSelectedChange, this);
  },

  search: function (query) {
    if (query === '') return this;
    query = query.toLowerCase();

    return _(this.filter(function (model) {
      var val = model.getName().toLowerCase();
      return ~val.indexOf(query);
    }));
  },

  _onSelectedChange: function (changedModel, isSelected) {
    if (isSelected) {
      this.each(function (m) {
        if (m.cid !== changedModel.cid) {
          m.set({
            selected: false
          }, {
            silent: true
          });
        }
      });
    }
  },

  getSelectedItem: function () {
    return _.first(
      this.where({ selected: true })
    );
  },

  setSelected: function (value) {
    var selectedModel;
    var silentTrue = { silent: true };
    this.each(function (mdl) {
      if (mdl.getValue() === value) {
        mdl.set({
          selected: true
        }, silentTrue);
        selectedModel = mdl;
      } else {
        mdl.set({
          selected: false
        }, silentTrue);
      }
    });
    return selectedModel;
  }

});
module.exports = Backbone.Collection.extend({
  constructor: function (models, options) {
    options = _.extend(options || {}, { silent: false });
    Backbone.Collection.prototype.constructor.call(this, models, options);
  },

  initialize: function () {
    this.bind('reset', this._setSelected, this);
    this.bind('change:selected', this._onSelectedChange, this);
    this._setSelected();
  },

  getSelected: function () {
    return this.find(function (model) {
      return model.get('selected');
    });
  },

  _setSelected: function () {
    var isSelected = this.getSelected();

    if (!isSelected && this.size() > 0) {
      this.at(0).set('selected', true);
    }
  },

  _onSelectedChange: function (itemModel, isSelected) {
    if (!isSelected) {
      return;
    }

    this.each(function (model) {
      if (model !== itemModel) {
        model.set('selected', false);
      }
    }, this);
  }
});
Example #24
0
 function createCollection(items, stubs) {
     var Collection = Backbone.Collection.extend(stubs);
     return new Collection(items);
 }
Example #25
0
var BaseCollection = Backbone.Collection.extend({

  dataUrl: null,

  cache: {},

  load: function(query, success, error) {

    this.loading = true
    this.empty = false
    this.reset()

    var q = query ? JSON.stringify(query) : ''

    setTimeout(function() {

      if ( this.cache.hasOwnProperty(q) ) {
        var result = this.cache[q]
        trigger.call(this, result, success)
        return
      }

      $.ajax({
        url: this.dataUrl,
        data: query,
        success: function(result) {
          trigger.call(this, result, success)
          this.cache[q] = result
        }.bind(this),
        dataType: 'json'
      })
    }.bind(this), 4)
  },

  isLoading: function() {
    return !!this.loading
  },

  isEmpty: function() {
    return !!this.empty
  },

  comparator: function(model) {
    var position = model.get('position')
    return typeof position != 'undefined' ? position : model.get('name')
  },

  getModel: function(needle) {
    var model = this.findWhere(needle)
    if ( model )
      return model
    return new this.model() // return empty model so react can still render
  }
})
Example #26
0
File: apps.js Project: osharim/desk
	return (function(){ 

		  AppBox = {
			  Models : {},
			  Views: {},
			  Collections : {},
		  }


		//var workspace_to_route = '/api/v1/apps/'+window.App.Navigate.workspace+'/';

		 AppBox.Models.AppBoxs = Backbone.Model.extend({});

		 AppBox.Collections.Box = Backbone.Collection.extend({ 

			 url : function() { 
				       
				       console.log(this)
				       return  "/api/v1/workspaceapps/?workspace="+this.models[0].id;
			      
			       },

		         model: AppBox.Models.AppBoxs ,// AppBoxs is a model 
			 
			 parse: function(response) { 

				  return response.objects;   

			}

		 });

		 AppBox.Views.Apps = Backbone.View.extend({  

			 initialize : function(){
				 
					      

					      //if( !window.App.Instances.App.Create){

				        		!new button_create_app();

				 	     // se muestra la seccion de nueva aplicacion
					    window.App.Sections.slideRightMainWindow();
					//$(".section_[data-nav=new_app]").hide()
					//$(".section_[data-nav=workspace]").hide()
					//$(".section_[data-nav=appbox]").show()

			 		console.log(this.options.navigate_to_workspace_by_id )

					AppBox.Collections.current_collection = new AppBox.Collections.Box( { id : this.options.navigate_to_workspace_by_id });
					AppBox.Collections.current_collection.on('add', this.append_new_app , this); 
					this.render();

			 },render : function(){

				  var that = this;
				AppBox.Collections.current_collection.fetch({ 

					beforeSend : function(){


						},

					success : function(data){ 

								//se vacia el contenedor
								$(".container_appbox ").html("");

								if(data.length != 0){

									that.update_models_in_controllers(); 
								}else{

								 //       $(".workspace_apps .status_workspace .no_apps").show();

								}
					}

				});


			},

			append_new_app: function(){ 

						     var collection_length = AppBox.Collections.current_collection.length;
						     var last_model = AppBox.Collections.current_collection.at(collection_length-1)  
						     this.renderApp(last_model)

			},

			update_models_in_controllers : function(){ 


			var that =this ;

			_.each (AppBox.Collections.current_collection.models , function(app_item){ 
					that.renderApp(app_item);
			});
						       
						       
			},

			 renderApp : function(app_item){ 


						  var AppView  = new unique_app({ 
							   model : app_item 

						  });
						var template_app = AppView.render().el;
						$(".container_appbox").append( template_app);

			}
				

		 });


		 return AppBox.Views.Apps;

	})();//closure
module.exports = Backbone.Collection.extend({
  url: function() {
    return app.serverConfigs.getActive().getServerBaseUrl() + '/get_chat_conversations';
  },

  model: ChatConversationMd,

  initialize: function() {
      this.on('change:unread', function(model){
          // Only re-sort collection if unread count was incremented
          if (model.hasChanged('unread') && model.get('unread') > 0) {
            this.sort();
          }
      });
  },

  comparator: function(a, b) {
    // Sort by unread messages first
    if (a.get('unread') > 0 && b.get('unread') == 0) {
      return -1;
    }
    
    if (a.get('unread') == 0 && b.get('unread') > 0) {
      return 1;
    }
    
    // then sort by timestamp
    if (a.get('timestamp') > b.get('timestamp')) {
      return -1;
    }
    
    if (a.get('timestamp') < b.get('timestamp')) {
      return 1;
    }
    
    return 0;
  }
});
Example #28
0
	},
	validation: {
		name: {
			required: true,
			msg: '请输入名称(中英文字母)'
		},
		nickname: {
			required: true,
			msg: '请输入编码(字母、_与数字的组合)'
		}
	},
});

//** 集合
var AppCollection = Backbone.Collection.extend({
	url: config.api.host + '/protect/apps',
	model: App,
});

//** list子视图
var AppListView = ListView.extend({
	el: '#list',

	initialize: function(options){
		var page = $(appTpl);
		var itemTemplate = $('#itemTemplate', page).html();
		this.template = _.template(_.unescape(itemTemplate || ''));
		this.collection = new AppCollection();
		ListView.prototype.initialize.apply(this,options);
	},
	getNewItemView: function(model){
		return this.template({model: model.toJSON()});
Example #29
0
var Backbone = require('backbone'),
    Chat = require('models/chat');


module.exports = Backbone.Collection.extend({
    model: Chat,
    fetch: function () {
        var self = this;
        //we just grab the first team for demo purposes
        app.api.getChatHistory(app.team.id, function (err, chats) {
            // Inflate our backbone models and collections
            self.reset(chats);
        });
    }
});
Example #30
0
var Backbone = require('backbone');

var Food = require('./food').Food;

var CartItem = Food.extend();

var CartCollection = Backbone.Collection.extend({
  model: CartItem,
  getCartTotal: function(){
    var price = this.reduce(function(memo, model){
      return (memo + model.get('price') / 100);
    }, 0);
    return '$' + price.toFixed(2);
  }
});


module.exports = {
  'CartItem': CartItem,
  'CartCollection': CartCollection
}