Files
old-ribica/front-ui/app/stores/itemStore.js

112 lines
2.5 KiB
JavaScript

var AppDispatcher = require('../dispatcher/appDispatcher');
var EventEmitter = require('events').EventEmitter;
var ItemConstants = require('../constants/itemConstants');
var ItemCollection = require('../models/itemCollection');
var ItemWithDetails = require('../models/itemWithDetails');
var _ = require('underscore');
// Define initial data points
var _items = new ItemCollection(),
_itemWithDetails = new ItemWithDetails();
var loadItemsForFrontpage = function() {
items = _items
items.setClassificationType(0);
items.setLimit(30);
items.setOffset(0);
items.fetch({
success: function() {
ItemStore.emitChange();
}
});
};
var getItemIdFromUrl = function() {
// ugly but it seems to me that
// router does not want to expose its
// state
var url = document.URL;
var itemIdRegex = /artikal\/(\d+)\//g;
var match = itemIdRegex.exec(url);
console.log(match);
return match[1];
};
var fetchItemWithDetails = function() {
var id = getItemIdFromUrl();
if (id !== undefined && _itemWithDetails.id !== id) {
var item = new ItemWithDetails({
id: id
});
item.fetch({
success: function() {
_itemWithDetails = item;
ItemStore.emitChange();
}
});
}
}
// Extend ItemStore with EventEmitter to add eventing capabilities
var ItemStore = _.extend({}, EventEmitter.prototype, {
// item with details
getLoadedItemWithDetails: function() {
return _itemWithDetails;
},
// Return All Items
getItems: function() {
return _items;
},
// Emit Change event
emitChange: function() {
console.log("Emitting change!");
this.emit('change');
},
// Add change listener
addChangeListener: function(callback) {
this.on('change', callback);
},
// Remove change listener
removeChangeListener: function(callback) {
this.removeListener('change', callback);
}
});
// Register callback with AppDispatcher
AppDispatcher.register(function(payload) {
var action = payload.action;
var text;
switch (action.actionType) {
case ItemConstants.LOAD_ITEM_WITH_DETAILS:
fetchItemWithDetails();
break;
case ItemConstants.LOAD_FOR_FRONTPAGE:
loadItemsForFrontpage();
break;
default:
return true;
}
// If action was responded to, emit change event
ItemStore.emitChange();
return true;
});
module.exports = ItemStore;