How to import json file into indexeddb? - json

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.

Related

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

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);
})

JSON data from web method for Donut chart

I am trying to provide a json string to google pie chart but every time its saying that json format is invalid. I have tried numerous ways to provide json string.
Please follow the code.
//ASP code
function drawDonutChart(chartType) {
//alert('Under Donut Chart');
var objCombo = {};
objCombo.siteURL = window.location.protocol + "//" + window.location.host + _spPageContextInfo.siteServerRelativeUrl;
objCombo.chartType = chartType;
var jsonData = $.ajax({
type: "POST",
contentType: 'application/json',
url: 'Dashboard.aspx/GetDonutChartData',
data: JSON.stringify(objCombo),
//beforeSend: function () { alert("before send"); },
//complete: function () { alert("complete"); },
success: function (data) {
var donutChartData = new google.visualization.DataTable(data.d);
var options = {
legend: 'right',
pieSliceText: 'value',
pieHole: 0.4,
chartArea: {
width: 300, left: 20, top: 20, right: 20, bottom: 10
}
};
if (donutChartData.getNumberOfRows() > 1) {
var donutChart = new google.visualization.PieChart(document.getElementById('programmatic_DonutChart'));
donutChart.draw(donutChartData, options);
}
else {
document.getElementById('programmatic_DonutChart').innerHTML = "No data to display!";
}
},
error: function (data) {
if ($("meta[name=debug]").attr("content") == "true") {
//Full Error when debugging
var errDoc = window.open();
errDoc.document.write(data.responseText);
errDoc.document.close();
}
else {
// generic error message for production use
alert("An unexpected error occurred.");
} return false;
}
});
return false;
}
//Web Method
[WebMethod]
public static string GetDonutChartData(string siteURL, string chartType)
{
string jsonData = "{'cols': [{'id':'','label':'Topping','pattern':'','type':'string'},"+
"{'id':'','label':'Slices','pattern':'','type':'number'}"+
"],'rows': [{'c':[{'v':'Mushrooms','f':null},{'v':3,'f':null}]},{'c':[{'v':'Onions','f':null},{'v':1,'f':null}]},{'c':[{'v':'Olives','f':null},{'v':1,'f':null}]},{'c':[{'v':'Zucchini','f':null},{'v':1,'f':null}]},"+
"{'c':[{'v':'Pepperoni','f':null},{'v':2,'f':null}]}]}";
//return list;
return jsonData;
}
//Error Message:
Uncaught Error: Invalid JSON string: "{'cols': [{'id':'','label':'Topping','pattern':'','type':'string'},{'id':'','label':'Slices','pattern':'','type':'number'}],'rows': [{'c':[{'v':'Mushrooms','f':null},{'v':3,'f':null}]},{'c':[{'v':'Onions','f':null},{'v':1,'f':null}]},{'c':[{'v':'Olives','f':null},{'v':1,'f':null}]},{'c':[{'v':'Zucchini','f':null},{'v':1,'f':null}]},{'c':[{'v':'Pepperoni','f':null},{'v':2,'f':null}]}]}"
Please help!!

Backbone sometimes load sometimes not

I have a Backbone app where I load external Json.
Sometimes I see the image inside the json(url) sometimes not, like the fetch doesn't finish in time.
Json that doesn't load sometimes are amenities (that contains url to image) and image (that contains url to image)
This is my app simplified:
HotelModel = Backbone.Model.extend({
initialize: function() {
// because initialize is called after parse
_.defaults(this, {
amenities: new AmenityCollection(),
image: new ImageCollection()
});
},
parse: function(response) {
if (_.has(response, "image")) {
this.image = new ImageCollection(response.image, {
parse: true
});
delete response.image;
}
if (_.has(response, "amenities")) {
this.amenities = new AmenityCollection(response.amenities, {
parse: true
});
delete response.amenities;
}
return response;
},
toJSON: function() {
var json = _.clone(this.attributes);
json.rooms = this.rooms.toJSON();
return json;
},
addAmenity: function(amenities, options) {
return this.amenities.add(amenities, options);
},
addRoom: function(rooms, options) {
return this.rooms.add(rooms, options);
},
addImage: function(image, options) {
return this.image.add(image, options);
}
});
AmenityModel = Backbone.Model.extend({});
ImageModel = Backbone.Model.extend({});
HotelCollection = Backbone.Collection.extend({
model: HotelModel,
}
});
AmenityCollection = Backbone.Collection.extend({
model: AmenityModel,
getAmenitiesByHotelId: function(hotelId) {
return this.where({
hotelId: hotelId
});
}
});
ImageCollection = Backbone.Collection.extend({
model: ImageModel,
getImagesByHotelId: function(hotelId) {
return this.where({
hotelId: hotelId
});
}
});
var CombinationView = Backbone.View.extend({
template: _.template($("#hotel-list-template").html()),
initialize: function(){
this.hotels = new HotelCollection([],{
url: '<?php echo base_url(); ?>json_upload/hotels_details_<?php echo($this->session->userdata("id")); ?>.json'
});
this.amenities = new AmenityCollection([], {
url: '<?php echo base_url(); ?>json_upload/hotels_details_amenities_<?php echo($this->session->userdata("id")); ?>.json'
});
this.image = new ImageCollection([], {
url: '<?php echo base_url(); ?>json_upload/hotels_details_images_<?php echo($this->session->userdata("id")); ?>.json'
});
this.hotels.on("sync", this.hotelsLoaded, this);
this.amenities.on("sync", this.amenitiesLoaded, this);
this.image.on("sync", this.imagesLoaded, this);
this.hotels.fetch();
},
render: function(){
this.$el.html('Loading...');
return this;
},
hotelsLoaded: function(){
this.image.fetch();
this.amenities.fetch();
},
amenitiesLoaded: function(){
this.hotels.each(function(hotel) {
hotel.addAmenity(this.amenities.getAmenitiesByHotelId(hotel.id));
}, this);
},
imagesLoaded: function(){
this.hotels.each(function(hotel) {
hotel.addImage(this.image.getImagesByHotelId(hotel.id));
}, this);
},
displayCombinations: function(){
$(this.el).html(this.template({hotels: this.hotels.models}));
}
});
Can someone explain me why sometimes i see the image in the template and sometimes not?
This is a little piece of template with some console.log
<% _.each(hotels, function(hotel1, index_hotel) { %>
<%
console.log('hotel:');
console.log(hotel1);
console.log('amenities');
console.log(hotel1.amenities.models); %>
<% _.each(hotel1.amenities.models, function(am) {
//NOT ENTER HERE SOMETIMES!!!
if(am.attributes.image!=''){
var src = '<?php echo(base_url()); ?>/img/backend/ameneties/' + am.attributes.image;
}
else{
var src = '<?php echo(base_url()); ?>/img/backend/ameneties/NO_IMG.jpg';
}
%>
<% }
}
%>
The first log of hotel show the full hotel and inside it I see amenities.models with all, but in the log of ameneties is empoty like is t was loaded before.

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});

backbone + binding

var ListView = Backbone.View.extend({
el: $('hello'),
events: {
'click .myName': 'namefunc',
},
initialize: function() {
var stuff = new FieldCollection();
stuff.parse();
var self = this;
stuff.fetch({
success: function (collection, response) {
console.log(response);
self.render(response);
return response;
}
});
},
render:function(output){
_.each(output, function(i){
p=i.name;
$(this.el).append("<button class='myName'>"+p+"</button><h1>"+i.img+"</h1><br/>");
},this);
},
namefunc:function(){
alert('hiii');
}
how to bind the change the hiii output of alert with the details of the person against whom the button is pressed...
{
"name": "john",
"img": "john.jpg",
"loc": "delhi",
"msg": "hello there"
}
this is the json which i m getting....when i click on button(having john name) it should show its msg....
If i've understood your question, you could just do something like...
var _self = this,
obj = Object;
$("<button>"+someVariable+"</button>")
.addClass('myName')
.appendTo(this.$el)
.on({
"click": function() { _self.fn(obj) }
});
​
initialize: function() {
var self = this;
_.bindAll(this, 'render');
this.collection = new FieldCollection();
this.collection.parse();
this.collection.fetch({
success: function (collection, response) {
console.log(response);
self.render();
}
});
},
render:function(){
var self = this;
_.each(this.collection, function(model) {
// here you should create subviews and delegate events within particular view
// i.e:
// self.buttonViews.push(new ButtonView({ model: model}));
// but for now you can use data-id attribute to match the button you clicked
$(self.el).append("<button class='myName' data-id=" + model.id + ">" + model.name + "</button><h1>" + model.img + "</h1><br/>");
});
},
namefunc:function(){
//use data-id attribute we put in button tag earlier to catch the id
//and use this.collection.get('id') function to get the model you want to get parameters of
}