Protractor cucumber html report is generating only after 2nd run? - html

When i try to run my code it is generating html report only after 2nd run.
In the first run it is generating the json file and then after the second run, by using the generated json file and creating the HTML report
Please tell me how to generate html report by running only once.
below is code i tried
hook.js
const {defineSupportCode} = require('cucumber');
defineSupportCode(function ({After}) {
After(function(scenario,done)
{
const world = this;
console.log('in after block')
if (scenario.result.status === 'failed') {
console.log('in after block inside')
browser.takeScreenshot().then(function (stream) {
let decodedImage = new Buffer(stream.replace(/^data:image\/(png|gif|jpeg);base64,/, ''), 'base64');
world.attach(decodedImage, 'image/png');
console.log('screenshot successful');
}).then(function () {
done();
});
}else {
done();
}
});
});
index.js
var reporter = require('cucumber-html-reporter');
var options = {
theme: 'bootstrap',
output: 'cucumber-report.html',
reportSuiteAsScenarios: true,
launchReport: true,
screenshotsDirectory: 'screenshots123',
takeScreenShotsOnlyForFailedSpecs: true,
//screenshotsSubfolder: 'images',
storeScreenshots: true,
};
reporter.generate(options);
Index.js
var reporter = require('cucumber-html-reporter');
var options = {
theme: 'bootstrap',
jsonFile: 'C:/Users/pc/ProtractorCucumber/htmlReport/cucumber_html_reporter/report.json',
// jsonFile: 'C:/Users/pc/ProtractorCucumber/htmlReport/cucumber_html_reporter/cucumber-report.json',
output: 'C:/Users/pc/ProtractorCucumber/htmlReport/cucumber_html_reporter/cucumber-report.html',
// output: 'report123.html',
reportSuiteAsScenarios: true,
launchReport: true,
screenshotsDirectory: 'screenshots123',
takeScreenShotsOnlyForFailedSpecs: true,
//screenshotsSubfolder: 'images',
storeScreenshots: true,
};
reporter.generate(options);

Cucumber-html-reporter will require the JSON file created by cucumber after the execution.
Please refer the following snippet which has exception handled before calling generate function of cucumber-html-report.
const Cucumber = require('cucumber');
import { browser } from 'protractor';
import * as fs from 'fs';
import { config } from '../config/config';
import { defineSupportCode } from "cucumber";
import * as reporter from 'cucumber-html-reporter';
import { mkdirp } from 'mkdirp';
defineSupportCode(function ({ registerHandler, registerListener, After, setDefaultTimeout }) {
setDefaultTimeout(10 * 1000);
let jsonReports = process.cwd() + "/reports/json";
let htmlReports = process.cwd() + "/reports/html";
let targetJson = jsonReports + "/cucumber_report.json";
//BeforeFeature
registerHandler('BeforeFeature', function (event, callback) {
browser.get(config.baseUrl);
callback();
});
After(function (scenario) {
let world = this;
if (scenario.isFailed()) {
return browser.takeScreenshot().then(function (screenShot) {
// screenShot is a base-64 encoded PNG
world.attach(screenShot, 'image/png');
});
}
})
let cucumberReporterOptions = {
theme: "bootstrap",
//theme: "foundation",
// theme: "simple",
jsonFile: targetJson,
output: htmlReports + "/cucumber_reporter.html",
reportSuiteAsScenarios: true,
launchReport: false
};
let logFn = string => {
if (!fs.existsSync(jsonReports)) {
mkdirp.sync(jsonReports);
}
try {
fs.writeFileSync(targetJson, string);
reporter.generate(cucumberReporterOptions); // invoke cucumber-html-reporter
} catch (err) {
if (err) {
console.log(`Failed to save cucumber test results to json file.
Failed to create html report.
`);
console.log(err);
}
}
};
let jsonformatter = new Cucumber.JsonFormatter({
log: logFn
});
registerListener(jsonformatter);
})

Related

PixelCompare method issue

I have an issue with PixelCompare extension.
Here, i am loading it:
viewer1 = new Autodesk.Viewing.GuiViewer3D(document.getElementById('forgeViewer1'), { extensions: [ 'GoogleMapsLocator', 'Autodesk.AEC.Minimap3DExtension','Autodesk.AEC.LevelsExtension','Autodesk.DocumentBrowser','Autodesk.ToolbarExtension' ,'Autodesk.Viewing.PixelCompare'] });
Then im trying to use it :
viewer1.compareTwoModels(data[0],data[1]);
Data is an array containing the models.
I get a "viewer.compareTwoModels is not a function" error which means either there is a typo in the function name or it doesnt exist.
Without access to the extension repo, i cannot confirm this method indeed exists.
Im at loss as to what to do and will welcome any help.
EDIT:
This snippet loads the document in the viewer to display it.
Autodesk.Viewing.Document.load(`urn:${urns[index]}`, function(doc){
var viewables=doc.getRoot().getDefaultGeometry();
doc.downloadAecModelData();
viewer1.loadDocumentNode(doc, viewables, {
placementTransform: (new THREE.Matrix4()).setPosition({ x: increment, y: 0, z: 0 }),
keepCurrentModels: true,
globalOffset: { x: 0, y: 0, z: 0 }
}).then(i => {
if(urns.length > 1) {
$(viewer1.toolbar.container).find('#toolbarXLS').hide();
}
});
increment += parseInt(sessionStorage.getItem('padding1'));
});
Then, im using this to pixel compare it:
viewer1.loadModel('urn:dXJuOmFkc2sud2lwcHJvZDpmcy5maWxlOnZmLmwwLS10X0k5UkVhbnNWRXBuLXl5Zmc_dmVyc2lvbj0x', {}, (model1) => {
console.log('test load model :' + model1)
viewer1.loadModel('urn:dXJuOmFkc2sud2lwcHJvZDpmcy5maWxlOnZmLmxXX0dONUJNVDBxdDRuOGZmRWx4SkE_dmVyc2lvbj0x', {}, async (model2) => {
const pcExt = await viewer1.loadExtension('Autodesk.Viewing.PixelCompare');
pcExt.compareTwoModels(model1, model2);
console.log()
});
});
I get an instant "file extension unsupported" error, probably on the first argument the code does not reach console.log('test load model :' + model1).
The function compareTwoModels is part of the extension object, not the viewer - see PixelCompare extension
function launchViewer() {
var options = {
env: 'Local'
};
Autodesk.Viewing.Initializer(options, () => {
viewer = new Autodesk.Viewing.GuiViewer3D(
document.getElementById('forgeViewer'), {}
);
viewer.start();
// Load 2 sheets
viewer.loadModel('scissors1.pdf', {}, (model1) => {
viewer.loadModel('scissors2.pdf', {}, async (model2) => {
// Compare them
const pcExt = await viewer.loadExtension('Autodesk.Viewing.PixelCompare');
pcExt.compareTwoModels(model1, model2);
});
});
});
}

babel es6 wrong exception location with react

i think this is a babel problem (not completely sure). The errors my javascript console throws are always wrong... No matter where the error occurs in my code it points to my handleFailure(serviceName, error) block... for instance... Calling this.foo(); after hand success occurs or even in i move this.foo(); to my getItemById method.. it always throws an error in the same block... What am i doing wrong in my store....
if i remove the bogus code it works just fine... i would like the error shown to me to reference the bogus code..
this is the error:
AircraftLocationStore.js:40 Server call aircraftLocationRest failed with error: aircraftLocationRest!handleFailure # AircraftLocationStore.js:40(anonymous function) # RestServiceClient.js:20
class AircraftLocationStore extends EventEmitter {
constructor() {
super();
this._populateRestCallStatus = RestCallStatus.NOT_REQUESTED;
this._dataStore = Map({});
this.handleSuccess = this.handleSuccess.bind(this);
this.handleFailure = this.handleFailure.bind(this);
}
populate(){
RestService.fetchData(this.handleSuccess, this.handleFailure, 'aircraftLocationRest');
this._populateRestCallStatus = RestCallStatus.STARTED
}
handleSuccess(serviceName, jsonData){
UT.logMethod(TAG, `${serviceName} succeeded!`)
jsonData.forEach((entity) => {
let tempEntity = AircraftLocationHelper.createFromJson(entity);
this._dataStore = this._dataStore.merge(Map.of(tempEntity.id, tempEntity))
});
UT.log('isMap', Map.isMap(this._dataStore))
this.foo();
this._populateRestCallStatus = RestCallStatus.SUCCESS;
this.emitChange();
}
handleFailure(serviceName, error){
//Utils.logMethod(TAG, 'handleFailure');
this._populateRestCallStatus = RestCallStatus.FAILED
console.error(`Server call ${serviceName} failed with error: ${serviceName}!`)
}
...
export default new AircraftLocationStore();
if i try and change an immutablejs record on my display component in the onChange it tells me this...
just in case i will include the code that handles the callback that ALWAYS throws the error
class RestServiceClient{
/**
* #param successCB
* #param failureCB
* #param endPoint
*/
fetchData(successCB, failureCB, endPoint) {
const serverUrl = BASE_URL + endPoint;
UT.log('serverUrl', serverUrl);
fetch(serverUrl).then(r => r.json())
.then(data => successCB(endPoint, data))
.catch(e => failureCB(endPoint, e.toString()))
}
}
export default new RestServiceClient();
here is my webpack.config
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: "source-map",
entry: "./src/index.js",
output: {
path: __dirname + "/build",
filename: "bundle.js"
},
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src'),
exclude: /node_modules/
}]
}
};
the problem appeared to be in my anonymous function that was created by the fat arrows =>
i rewrote:
fetch(serverUrl).then(r => r.json())
.then(data => let foo = data; successCB(endPoint, data))
.catch(e => failureCB(endPoint, e.toString()));
as:
fetch(serverUrl)
.then(
function(response) {
if (response.status !== 200) {
failureCB(endPoint, 'Looks like there was a problem. Status Code: ' + response.status);
}
// Examine the text in the response
response.json().then(function(data) {
successCB(endPoint, data)
});
}
)
.catch(function(err) {
failureCB(endPoint, 'Looks like there was a problem. Status Code: ' + err);
});
and i once again have some meaningfull error messages...

How to import json file into indexeddb?

I am doing an app that store some data in the IndexedDB, but I want to load first some data that is in my json file.
Here is my json file:
{
"ciudades":[
{
"ciudad":"Asuncion",
"latitud":-25.2985296,
"longitud":-57.6710677
},
{
"ciudad":"Caaguazu",
"latitud":-25.465034,
"longitud":-56.0183859
},
{
"ciudad":"Ciudad del Este",
"latitud":-25.4933441,
"longitud":-54.6710438
},
{
"ciudad":"San Pedro",
"latitud":-24.1586759,
"longitud":-56.636503
},
{
"ciudad":"Pedro Juan Caballero",
"latitud":-22.5450875,
"longitud":-55.7618963
}
]
}
you follow step
step 1 read mozilla site
step 2 create indexedDB
var ciudades = [
{
"ciudad":"Asuncion",
"latitud":-25.2985296,
"longitud":-57.6710677
},
{
"ciudad":"Caaguazu",
"latitud":-25.465034,
"longitud":-56.0183859
},
{
"ciudad":"Ciudad del Este",
"latitud":-25.4933441,
"longitud":-54.6710438
},
{
"ciudad":"San Pedro",
"latitud":-24.1586759,
"longitud":-56.636503
},
{
"ciudad":"Pedro Juan Caballero",
"latitud":-22.5450875,
"longitud":-55.7618963
}
];
var IDBSetting = {
name: "indexedDBName",
version: 1,
tables: [{
tableName: "ciudades",
keyPath: "seq",
autoIncrement: true,
index: ["ciudad", "latitud", "longitud],
unique: [false, false, false]
}]
};
! function() {
console.log("indexeDB init");
var req = indexedDB.open(IDBSetting.name, IDBSetting.version);
req.onsuccess = function(event) {
console.log("indexedDB open success");
};
req.onerror = function(event) {
console.log("indexed DB open fail");
};
//callback run init or versionUp
req.onupgradeneeded = function(event) {
console.log("init onupgradeneeded indexedDB ");
var db = event.target.result;
for (var i in IDBSetting.tables) {
var OS = db.createObjectStore(IDBSetting.tables[i].tableName, {
keyPath: IDBSetting.tables[i].keyPath,
autoIncrement: IDBSetting.tables[i].autoIncrement
});
for (var j in IDBSetting.tables[i].index) {
OS.createIndex(IDBSetting.tables[i].index[j], IDBSetting.tables[i].index[j], {
unique: IDBSetting.tables[i].unique[j]
});
}
}
}
}();
step 3 addData
var IDBFuncSet = {
//write
addData: function(table, data) {
var req = indexedDB.open(IDBSetting.name, IDBSetting.version);
req.onsuccess = function(event) {
try {
console.log("addData indexedDB open success");
var db = req.result;
var transaction = db.transaction([table], "readwrite");
var objectStore = transaction.objectStore(table);
var objectStoreRequest = objectStore.add(data);
} catch (e) {
console.log("addDataFunction table or data null error");
console.log(e);
}
objectStoreRequest.onsuccess = function(event) {
//console.log("Call data Insert success");
}
objectStoreRequest.onerror = function(event) {
console.log("addData error");
}
};
req.onerror = function(event) {
console.log("addData indexed DB open fail");
};
}
}
for(var i in ciudades){
IDBFuncSet.addData("ciudades",ciudades[i]);
}
step 4 getData
IDBFuncSet.getAllData = function(arr, table) {
try {
var req = indexedDB.open(IDBSetting.name, IDBSetting.version);
req.onsuccess = function(event) {
var db = req.result;
var transaction = db.transaction([table], "readonly");
var objectStore = transaction.objectStore(table);
var objectStoreRequest = objectStore.openCursor();
objectStoreRequest.onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
arr.push(cursor.value);
cursor.continue();
} else {
}
}
};
req.onerror = function(event) {
console.log("getAllData indexed DB open fail");
};
} catch (e) {
console.log(e);
}
}
var ciudadesArr = [];
IDBFuncSet.getAllData(ciudadesArr, "ciudades");
console.log(ciudadesArr);
I hope this helps
Here's how I've done mine, thanks to the android-indexeddb package.
angular.module('yourApp', ['indexedDB'])
.config(function($indexedDBProvider) {
$indexedDBProvider
.connection('dbName')
.upgradeDatabase(1, function(event, db, tx) {
var objStore = db.createObjectStore('storeOne', { keyPath: 'stop_id' });
objStore.createIndex('store_id', 'store_id', { unique: false });
})
// the next upgradeDatabase() function is necessary if you
// wish to create another datastore
.upgradeDatabase(2, function(event, db, tx) {
var secondObjectStore = db.createObjectStore('storeTwo', { keyPath: 'my_id' });
secondObjectStore.createIndex('another_id', 'another_id', { unique: false });
});
})
Then in my controller:
angular.module('yourApp')
.controller('homeCtrl', ['$scope', '$http', '$indexedDB', function($scope, $http, $indexedDB) {
$scope.objects = [];
var loadJSON = function(file_name) { ... //load the json file in here}
$indexedDB.openStore('storeOne', function(store) {
var loaded = loadJSON('file_name.json');
store.upsert(loaded).then(function(e) {
console.log('added successfully');
});
});
$indexedDB.openStore('times', function(store) {
var loaded = loadJSON('file_name.json');
store.upsert(loaded).then(function(e) {
console.log('added successfully');
});
});
}]);
Check out the project page to learn more of the tricks up this package's sleeves.
Although this angular-indexeddb page supports queries, for advanced queries like joins, you might wanna consider ydn-db
Getting some pretty nice workflow with both packages.
For the loadJSON() function, it could be something like this:
var loadJSON = function(file_name) {
var data;
$.ajax({
url: '../data/' + file_name,
dataType: 'json',
async: false,
success: function(res_data) {
data = res_data;
console.log('Loaded ' + file_name + ' nicely');
},
error: function(err) {
console.log('error happened');
}
});
return data;
}
There is File API, but that doesn't seem to be a solid standard yet.
What I do at the moment, is have the user open the file, copy it's contents to Clipboard, and paste it into a TextArea element on my web page.
In JavaScript I add a listener to the TextArea's change event and parse the text content into JSON, which is then written to indexedDB.

Convert Json into Xlsx File

I am trying to covert json data into Xlsx file and save it in a folder.
I have been trying to use icg-json-to-xlsx module but till now I have been unable to use it.
My code looks like this:
jsonXlsx = require('icg-json-to-xlsx');
filename = path.join('./files', "output.xlsx");
outputFile = jsonXlsx(filename, result) //result contains json data
console.log(outputFile);
but I got this error
outputFile = jsonXlsx(filename, result)
^
TypeError: Property 'jsonXlsx' of object # is not a function
Getting data from mongodb:
in routes:
router.get('/', function(req, res, next) {
fileController.getAll(function(err, result){
if(err){
res.send(500,err);
}
// res.json(result);
var data = result;
in controller:
FileController.prototype.getAll = function(callback){
File.find( {}, {_id: false, id: true, name: true, status: true}, function(err, file){
if(err) {
return callback(err);
} else {
if (!file) {
return callback('file not found');
}
}
callback(null, file);
}
)};
Try this
outputFile = jsonXlsx.writeFile(filename, result);
jsonXlsx is object, which contains methods like writeFile, writeBuffer, so you can't call jsonXlsx as function... or you need add reference to function like this
jsonXlsxWriteFile = require('icg-json-to-xlsx').writeFile;
outputFile = jsonXlsxWriteFile(filename, result)
Example
var jsonXlsx = require('icg-json-to-xlsx');
var path = require('path');
var filename = path.join('./files', "output.xlsx");
var result = [
{ id: '1', name: 'test', status: '123' },
{ id: '2', name: 'david', status: '323'},
{ id: '3', name: 'ram', status: '2323' }
];
var outputFile = jsonXlsx.writeFile(filename, JSON.stringify(result));
console.log(outputFile);
Update:
File
.find({ })
.select({
_id: false, id: true, name: true, status: true
})
.lean()
.exec(function(err, file) {
//
});
In your case, query returns MongooseDocuments, but jsonXlsx needs plain JavaScript objects, so that's why you should use lean()
You can try Alasql JavaScript SQL library. It includes a module to work with JSON and XLSX files (with support of js-xlsx.js library).
Install these two libraries into your project.
npm install alasql
npm install xlsx
Then call alasql function:
var alasql = require(alasql);
alasql('SELECT * INTO XLSX("mydata.xlsx",{headers:true}) \
FROM JSON("mydata.json")');
var cities = [{City:'London',Population:2500000},{City:"Paris",Population:2000000}];
alasql("SELECT * INTO XLSX("mydata.xlsx",{headers:true}) FROM ?",[cities]);
See more examples in this demo file.
There are a lot of modules that can do it. But if you want to control the formatting of xlsx file, then I suggest you use this below code. Rows contain data in the form of JSON array.
var excel = require('node-excel-export');
var styles = {
headerDark: {
fill: {
fgColor: {
rgb: 'FF000000'
}
},
font: {
color: {
rgb: 'FFFFFFFF'
},
sz: 14,
bold: true,
underline: true
}
},
cellPink: {
fill: {
fgColor: {
rgb: 'FFFFCCFF'
}
}
},
cellGreen: {
fill: {
fgColor: {
rgb: 'FF00FF00'
}
}
}
};
var specification = {
"Col1": {
"displayName": 'Col1Name',
"headerStyle": styles.headerDark,
"width": 250
},
"Col2": {
"displayName": 'Col2Name',
"headerStyle": styles.headerDark,
"width": 215
},
"Col3": {
displayName: 'Col3Name',
headerStyle: styles.headerDark,
width: 150
}
}
var report = excel.buildExport(
[{
name: 'Report.xlsx',
specification: specification,
data: rows
}]
);

backbone fetch specific object from json file, not rendering

Okay, im going slightly insane trying to display data from a json file in 2 seperate views/collections.
I will paste my entire code here and try to explain where i am now, and what i need done.
Its probably a very small thing i just need to do in order for it to work, but i cant see it..
Here is a screen shot of how my page looks like now, as you can see the data is being loaded, i just cant get it into the views properly..
In my Collection class i call parse:
parse:function(response, options) {
return options.parseField ? response[options.parseField] : response;
},
i call sync: (not sure its needed at all)
sync: function(method, model, options) {
options.contentType = "application/json";
options.cache = false;
options.dataType = "json";
return Backbone.sync(method, model, options);
},
Then near the bottom, i create 2 new collections and use fetch to get the specific json data i need for each collection like so:
var links = new App.Collections.Links();
links.fetch({
parseField: 'links_1',
success: function () {
console.log(links.toJSON());
return links.toJSON();
}
});
var links2 = new App.Collections.Links();
links2.fetch({
parseField: 'links_2',
success: function () {
console.log(links2.toJSON());
return links2.toJSON();
}
});
I do console.log and can see that my json data is getting loaded just fine, but its not getting rendered ?
What am i doing wrong here..
For sake of debugging and understanding i have included my entire js file below.
(function() {
// Helper functions
// Defining namespacing rules
window.App = {
Models: {},
Collections: {},
Views: {}
};
// Setting global template function, for simpel declaration later on by setting template('name'); for the built in template function.
window.template = function(id) {
return _.template( $('.' + id).html() );
};
// Capitalize first letter in a link by adding .capitalize(); to the string.
String.prototype.capitalize = function() {
return this.charAt(0).toUpperCase() + this.slice(1);
};
// Extending Backbone
//Modellen
App.Models.Link = Backbone.Model.extend({
defaults: {
navn : 'i haz a name!',
link : 'http://www.lolcats.com/',
counter : 0
}
});
//Collection
App.Collections.Links = Backbone.Collection.extend({
model: App.Models.Link,
url: 'data1.json',
parse:function(response, options) {
return options.parseField ? response[options.parseField] : response;
},
sync: function(method, model, options) {
options.contentType = "application/json";
options.cache = false;
options.dataType = "json";
return Backbone.sync(method, model, options);
},
// Sort the models 'highest first'
comparator: function(link) {
return -link.get('counter');
}
});
//Singel view
App.Views.LinkView = Backbone.View.extend({
tagnavn: 'li',
template: template('Links'),
initialize: function() {
this.model.on('change', this.render, this);
this.model.on('destroy', this.remove, this);
},
events: {
'click .edit' : 'retLink',
'click .delete' : 'destroy',
'click .LinkUrl' : 'addCounter'
},
retLink: function() {
var newLinkNavn = prompt('What should the new name be?', this.model.get('navn'));
if ( !newLinkNavn ) return;
newLinkNavn = newLinkNavn.capitalize();
this.model.set('navn', newLinkNavn);
var newLinkUrl = prompt('What should the new url be?', this.model.get('link'));
if ( !newLinkUrl ) return;
this.model.set('link', newLinkUrl);
},
destroy: function() {
this.model.destroy();
},
// Increment the counter then user clicks it
addCounter: function(e) {
e.preventDefault();
var newCounter = this.model.get('counter');
this.model.set('counter', newCounter + 1);
},
remove: function() {
this.$el.remove();
},
render: function() {
this.$el.html(this.template(this.model.toJSON()) );
return this;
}
});
//Collection View
App.Views.LinksView = Backbone.View.extend({
tagName: 'ul',
className: 'liste',
initialize: function() {
_.bindAll(this);
this.collection.on('add', this.addOne, this);
this.collection.on('reset', this.render);
// Render view when a user has changed a model
this.collection.bind('change', this.render, this);
$('.navnClass').focus();
this.load();
this.render();
},
load: function() {
this.collection.fetch({
add: true,
success: this.loadCompleteHandler,
error: this.errorHandler
});
},
loadCompleteHandler : function(){
this.render();
},
errorHandler : function(){
throw "Error loading JSON file";
},
render: function() {
// Empty the UL before populating it with the new models and sorting it.
this.$el.empty();
this.collection.sort();
this.collection.each(this.addOne, this);
return this;
},
addOne: function(link) {
var linkView = new App.Views.LinkView({ model: link });
this.$el.append(linkView.render().el);
}
});
// Create link view
App.Views.AddLink = Backbone.View.extend({
el: '#addLink',
events: {
'submit' : 'submit'
},
submit: function(e) {
e.preventDefault();
var linkNavn = $(e.currentTarget).find('.navnClass').val(),
linkNum = $(e.currentTarget).find('.linkClass').val();
// Tildel link navn en værdi, hvis det er tomt
if ( ! $.trim(linkNavn)) {
linkNavn = 'I haz a name!';
}
// Tildel link url en værdi, hvis det er tomt
if( ! $.trim(linkNum)) {
linkNum = 'http://www.lolcats.com/';
}
// Tilføj http:// foran værdi, hvis den ikke indeholder det i forvejen.
if( linkNum.indexOf( "http://" ) == -1 ) {
addedValue = 'http://',
linkNum = addedValue + linkNum;
}
// nulstil og sæt fokus på link navn feltet.
$(e.currentTarget).find('.navnClass').val('').focus();
$(e.currentTarget).find('.linkClass').val('');
this.collection.add({ navn:linkNavn, link: linkNum });
}
});
// new links collection
// populate collection from external JSON file
// change navn to match the link heading
var links = new App.Collections.Links();
links.fetch({
parseField: 'links_1',
success: function () {
console.log(links.toJSON());
return links.toJSON();
}
});
var links2 = new App.Collections.Links();
links2.fetch({
parseField: 'links_2',
success: function () {
console.log(links2.toJSON());
return links2.toJSON();
}
});
// new collection view (add)
var addLinkView = new App.Views.AddLink({ collection: links });
// new collection view
var linksView = new App.Views.LinksView({ collection: links });
$('.links').html(linksView.el);
// new collection view
var linksView2 = new App.Views.LinksView({ collection: links2 });
$('.links2').html(linksView2.el);
})();
Could you try this:
var links2 = new App.Collections.Links();
links2.on("reset", function(collection){
console.log("reset event", collection);
}
links2.fetch({
parseField: 'links_2',
wait:true, #wait for the server to respond
success: function (collection, response) {
console.log(collection, response);
}
});
a return in the success call doesn't do anything (it would return to the $.ajax object). I've added a wait because it would call the successcall instantly if it passes the clientside validation (you have none, so it would always call success first).
You say it doesn't render anything. But to render something you need a View. I don't see a view in your code.
Here's a quick example of the view:
var Link = new Backbone.View.extends({
el: $('body'),
initialize: function(){
this.listenTo(this.collection, 'reset', this.render, this)
},
render: function(){
this.$el.empty();
this.collection.each(function(item){
this.$el.append(item.get('id') + '<br />');
});
}
})
var view = new Link({collection: links2});