Getting JSON in to Underscore Template in Backbone - json

Just getting started with Backbone and still making sense of the ins and outs.
I'm trying to simply display some JSON using Underscore and Backbone. I'm able to make it to work just using Underscore and $.getJSON, but when I try to wire it up with Backbone I get a variety of errors depending upon what I try.
I've also been able to get Backbone to work by hardcoding values in to the model, but I'm running in to a wall when I try to bring it all together. Any help is appreciated.
Here is my Underscore template:
<script type="text/html" id='trailTemplate'>
<% _.each(trails,function(trail){ %>
<%= trail.trailname %><br />
<% }); %>
</script>
And here is my Backbone code:
var Trail = Backbone.Model.extend({
urlRoot: "trails.json"
});
var trail = new Trail({});
var TrailView = Backbone.View.extend({
el: '.page',
template: _.template($("#trailTemplate").html(), {trails:trail.fetch()}),
render: function(){
this.$el.html(this.template(this.model.toJSON()));
return this;
}
});
var trailView = new TrailView({
model: trail
});
trailView.render();
And in case you need it, here is trails.json
[
{
"trailhead": "Bear Lake",
"trailname": "Bear Lake",
"distance": ".5",
"gain": "20",
"level": "easy"
},
{
"trailhead": "Bear Lake",
"trailname": "Nymph Lake",
"distance": ".5",
"gain": "225",
"level": "fairly easy"
}
]

Your trails.json file contains an array with 2 objects, which both represent a single 'Trail'. So you should have a collection 'Trails' instead of a single model
var Trails = Backbone.Collection.extend({
url: '/trails.json'
});
var trails = new Trails();
The underscore template function can be used in 2 ways:
_.template(templateString) - compiles the templateString into function that can be evaluated when necessary
_.template(templateString, data) - compiles and immediately evaluates the template with the given data
Now the way you are using is number 2 (the way you declare the template) combined with number 1 (how you use it inside render). Let's examine the template declaration:
template: _.template($("#trailTemplate").html(), {trails:trail.fetch()})
This is all good up until the point you try to give it the data -attribute. First of all you don't need to give the data at this point, you just want to create the template function that can be evaluated when the View renders. Second, the stuff you are trying to pass as data is not at all what you think it is.
trail.fetch() doesn't return the the fetch results, it returns the ajax handle for the ajax call that is made with fetch. Thankfully Backbone is made so you don't have to think about all this painful ajax stuff, but instead you can trust the events that Backbone emits. So whip out the Backbone Catalog o' Events and check out reset
"reset" (collection, options) — when the collection's entire contents have been replaced.
This is the event you collection will emit, after fetch (also sync, i think). Before this event is emitted, your collection will be empty, so there is no point in doing anything with it before hearing this reset event. So let's bring it all together now:
var TrailView = Backbone.View.extend({
el: '.page',
template: _.template($("#trailTemplate").html()), // no data attribute here
initialize: function() {
this.collection.on('reset', this.render); // render after collection is reset
this.collection.fetch(); // fetch the collection from the trails.json file
}
render: function(){
// evaluate the template here
this.$el.html(this.template(this.collection.toJSON()));
return this;
}
});
var trailView = new TrailView({
collection: trails
});
// trailView.render(); <- No need for this, because it will render itself
Hope this helps!

Related

How to get client side data from Kendo Grid to controller

I am trying to get Kendo Grid data which is hydrated from client side to a MVC controller method. My view contains several single fields like name, date of birth etc and tabular field which I hooked with a Kendo Grid. Since its a new operation I have no data in the grid ( and other fields) and user enters them from client side.
I have no idea how to proceed on this. Ideally I would like to get this data to a list in my viewmodal. So that when the user hits save, I have all other data and the grid data coming into a controller method.
I am able to successfully bind a list with kendo grid and display it. I have very little experience on JavaScript and Kendo and web programming.
If any of you can point me to the right direction, sample code would be greatly appreciated.
$("#departmet").kendoGrid({
dataSource: dataSource,
height: 250,
scrollable: true,
sortable: true,
filterable: true,
pageable: {
input: true,
numeric: false
},
columns: [
"DepartmentName",
"SubDivision"
]
});
From experience I know their documentation is not easy to navigate. It seems there is the documentation and then the API. The API is usually what you will always want to find. What you will need is the information from here https://docs.telerik.com/kendo-ui/api/javascript/ui/grid. If I understand the question correctly. There are several ways you can achieve posting. You could make use of editor templates. Click the Open in Dojo to get an idea how it looks.
https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/configuration/editable.template
With this you do not have to worry about modifying the data via javascript. Assuming your grid is surrounded with a form element it will get posted when submitted. Note paging is not accounted for here. Also, this method by default can auto post after each edit. If you don't want this behavior then you will have to have advanced knowledge of the API.....Correction on that last statement. The API is different when dealing with the data all on the client side. Click the Open in Dojo to see it all on the client side. If you are not wanting to use editor templates and want to manage the data editing yourself then you need to use the grid methods provided.
Once you have your grid created. To access the data source of the grid you will need to get the dataSource.
$('#departmet').data('kendoGrid').dataSource;
https://docs.telerik.com/kendo-ui/api/javascript/data/datasource
If you need to use a different data source(or change it) you can use the setDataSource method below(grid function).
https://docs.telerik.com/kendo-ui/api/javascript/ui/grid/methods/setdatasource
To add to the data source use the add function to add a new object.
$('#departmet').data('kendoGrid').dataSource.add({ id: 2, name: 'name'});
https://docs.telerik.com/kendo-ui/api/javascript/data/datasource/methods/add
It is important with kendo to ALWAYS use the methods provided to change the data source so that the proper events can fire to update the UI accordingly. This includes if you need to set a property on a specific data item. In that case you need to use the set method on the item itself.
After you are done modifying your data. Within javascript get the data and either create DOM elements within a form
//JQuery sudo code example
var data = $("#departmet").data("kendoGrid").dataSource.data();
var dataLen = data.length;
var myForm = $('#my-form'); //Already within DOM
for (var i = 0; i < dataLen; i++) {
var item = data[i];
var idEl = $('<input type="hidden" name="userData[' + i + '].id" />');
idEl.val(item.id);
var nameEl = $('<input type="hidden" name="userData[' + i + '].name" />');
nameEl.val(item.name);
myForm.append(idEl);
myForm.append(nameEl);
}
myForm.submit();
This assumes your controller function(??) on the backend is expecting an array of objects with the property name of userData.
Alternatively, you can post it via ajax. For example, the ajax jquery function. Passing your data as the data of the ajax call.
http://api.jquery.com/jquery.ajax/
Don't want to ramble. Let me know if you need more help.
SO won't let me comment yet so have to add another answer. You will not need to define the data source within the .NET code when dealing with client only data. Just use this.
.DataSource(dataSource => dataSource
.Ajax()
.ServerOperation(false)
)
If you will have data coming from the backend then you need to use the generic-less constructor and pass in the object else keep what you have.
Html.Kendo().Grid(Model.MyList)
However, if you are preprocessing some client data on the screen that you want to initialize then you will need to do this on ready. Don't worry about the schema part of the data source. It already knows this when you used the .NET MVC wrapper because you gave it the schema(type) via the generic or the parameter provided.
var initialDS= new kendo.data.DataSource({
data: [
{ ActionName: "Some Name", ActionType: "Some Type" }
]
});
$(document).ready(function () {
$('#docworkflow').data('kendoGrid').setDataSource(initialDS);
});
As I mentioned in the other answer. Use the data source functions for adding additional data to the data source. No need to setDataSource each time you want to add. Just
//Assuming you have 2 inputs on the screen the user is entering info into
var nameEntry = $('#action-name').val();
var typeEntry = $('#action-type').val();
$('#docworkflow').data('kendoGrid').dataSource.add({ ActionName: nameEntry , ActionType: typeEntry });
So after some efforts I come up with. But I don't know where to specify the
data in the html code. Is it possible this way?
#(Html.Kendo().Grid <DockData.Action> ()
.Name("docworkflow")
.Columns(columns =>
{
columns.Bound(e => e.ActionName);
columns.Bound(e => e.ActionType);
}).DataSource( **How do I load a script variable here***)
//This script variable should be fed to the above code.
This variable is populatedwhen the user adds data from the UI which works fine.
var dataSource = new kendo.data.DataSource({
data: result,
schema: {
model: {
fields: {
ActionName: { type: "string" },
ActionType: { type: "string" }
}
}
},
pageSize: 20
});

vue.js json object array as data

aye folks!
I'm currently learning to do stuff with vue.js. unfortunately i'm stuck atm. what i want to do is sending a request to my sample API which responds with a simple json formatted object.
I want to have this object as data in my component – but it doesn't seem to do that for whatever reason.
Ofc i tried to find a solution on stackoverflow but maybe i'm just blind or this is just like the code other people wrote. i even found this example on the official vue website but they're doing the same thing as i do .. i guess?
btw. When i run the fetchData() function in a separate file it does work and i can access the data i got from my API. no changes in the code .. just no vue around it. i'm really confused right now because i don't know what the mistake is.
code:
var $persons = [];
and inside my component:
data: {
persons: $persons,
currentPerson: '',
modal: false
},
created: function() {
this.fetchData()
},
methods: {
fetchData: function () {
var ajax = new XMLHttpRequest()
ajax.open('GET', 'http://api.unseen.ninja/data/index.php')
ajax.onload = function() {
$persons = JSON.parse(ajax.responseText)
console.log($persons[0].fname)
}
ajax.send()
}
},
[...]
link to the complete code
First, make sure that the onload callback is actually firing. If the GET request causes an error, onload won't fire. (In your case, the error is CORS-related, see this post suggested by #Pradeepb).
Second, you need to reference the persons data property directly, not the $persons array that you initialized persons with.
It would look like this (inside your fetchData method):
var self = this;
ajax.onload = function() {
self.persons = JSON.parse(ajax.responseText)
console.log($persons[0].fname)
}

How do I format my AngularJS data model?

Hi I am just beginning with angular and I am struggling to find the answer to what I'm sure is quite a simple thing to do.
I am currently getting the values of some input boxes and pushing them into my scope. This is creating one long 'array' eg:
['data-1','data-2','data-3']
I would like to format my data in the following way instead
$scope.data = [
{
'header1': 'data1-1',
'header1': 'data1-2',
'header1': 'data1-3'
},
{
'header1': 'data2-1',
'header1': 'data2-2',
'header1': 'data2-3'
}
]
This is my function as it currently is.
$scope.createRow = function(){
angular.forEach(angular.element("input"), function(value, key){
$scope.td.push($(value).val());
});
}
Any help or pointers would be greatly appreciated as I am just getting my head round the angular way
Doing this isn't hard... but before I give you a gun to shoot yourself in the foot, just to say that I think it would be beneficial to explain WHY you want structure in that other format you are mentioning. You seem to have lots of data repetition and that's always a red flag.
Now for the code, you just need to create object before pushing it to the array like:
$scope.createRow = function(){
angular.forEach(angular.element("input"), function(value, key){
var obj = {
"header1": val + "-1",
"header2": val + "-2"
};
$scope.td.push(obj);
});
}
EDIT:
OK, so you are trying to add new row to the table. First of all, you shouldn't be doing angular.forEach, but rather those input elements in HTML should bind to existing scope object, like:
// obviously use better names than Input1Value
// I am here just giving you example
$scope.bindData = {
Input1Value: null,
Input2Value: null
};
// in HTML you will do
// <input ng-model="bindData.Input1Value" />
// <input ng-model="bindData.Input2Value" />
Now that you've eliminated that nasty angular.forEach you need to have some kind of event handler, for example when user clicks the button you want to add this object to the array to which table is data bound. Just be sure to clone the $scope.bindData object when you add it to array.
$scope.createRow = function(){
var newRowData = $scope.cloneObject($scope.bindData);
$scope.td.push(newRowData);
}
// http://heyjavascript.com/4-creative-ways-to-clone-objects/
// https://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object
$scope.cloneObject = function(objToClone) {
var newObj = (JSON.parse(JSON.stringify(objToClone)));
}
To close this answer off - keep in mind, if you ever find yourself directly referencing HTML DOM elements in Javascript with AngularJS - you are doing something wrong. It's a nasty habit to eliminate, especially if you are coming from jQuery background (and how doesn't?), where everything is $("#OhHiThere_ElementWithThisId).
Obviously the main thread on this topic on StackOverflow is this one:
“Thinking in AngularJS” if I have a jQuery background?
However I find that it's too theoretical, so Google around and you may find better overviews like:
jQuery vs. AngularJS: A Comparison and Migration Walkthrough

BackboneJS - Multiple Collections in one view

I have a leftMenu section where I want to display 4 menus which are categorized by each subject. Every menu is a list and I want them to be displayed in the same View. I created 4 JSON files and to each one of them a Collection and a Model.
Usually i do it like this, first i define in router
this.mainMenuCollection = new MainMenuCollection();
this.mainMenuView = new MainMenuView({el:'#nav', collection:this.mainMenuCollection});
So, now I have these 4 collections defined in the router which I want in one view:
this.allcategoryMenuCollection = new AllCategoryMenuCollection();
this.natcategoryMenuCollection = new NatCategoryMenuCollection();
this.intcategoryMenuCollection = new IntCategoryMenuCollection();
this.topcategoryMenuCollection = new TopCategoryMenuCollection();
usually i render the collection in the View like this:
$(this.el).html(this.template({mainmenu:this.collection.toJSON()}));
Please help
Send in the collections as an object when you create your view:
this.mainView = new MainView({
el:'#nav'
});
this.mainView.collections = {
allcategoryMenuCollection: this.allcategoryMenuCollection
natcategoryMenuCollection: this.natcategoryMenuCollection
intcategoryMenuCollection: this.intcategoryMenuCollection
topcategoryMenuCollection: this.topcategoryMenuCollection
}
Access your collections inside the view by calling this.collections.collectionName
This may not seem like a semantically accurate way to do it, but to take advantage of backbone automatically assigning the model and collection properties in options, I do this:
var view = new MyView({
collection: {
comments: new CommentsCollection(),
images: new ImagesCollection()
}
});
Works for me. Otherwise you have to put a line in the initialize function to extend this, or use a base class. Personally I find this more elegant, even if it's missing a couple of pluralised properties.
Then, later on, you can use this.collection.comments.toJSON() for your template properties.
There's nothing wrong with housing a number of sub-views within an outer view. Your outer view could be something as simple as this. If you need to wait for all of your collections to be fetched before you render you could try:
var MyView = Backbone.View.extend({
initialize : function (options) {
var done, collections = options.collections;
done = _.invoke(collections, 'fetch');
$.when.apply($, done).done(this.onDataReady);
},
onDataReady : function () {
// Make a second pass at render after setting the flag.
this.ready = true;
this.render();
},
render : function () {
if(this.ready === true) {
// Now render the whole lot.
} else {
// Any non-data depending rendering.
}
}
});
Then you can either initialize the outer view and pass an array of collections in:
var view = new MyView({
collections: [...]
});
If you don't need all the collections to have fetched their data before hand it's even simpler. Just pass in the collections array and set them up as you need:
var MyView = Backbone.View.extend({
initialize : function (options) {
this.collectionA = options.collections[0];
},
render : function () {
}
});

using multiple json request with backbone.js

I have recently started working with backbone.js and i am finally started to get my head around after many tutorials.
One thing i am stuck on is how to use the routing to allow a list to pull different rest request.
Say i have the following in my collection
var NewsCollection = Backbone.Collection.extend({
model : News,
url: 'http://api.example.com/index.php/news/all/format/json',
});
From my understanding correct me if i am wrong backbone stores all the data pulled from the above feed into my model that extends this collection, this will all work i will pull in the feed and then display it in the view
This is where i get confused within my routing i have the following.
var NewsRouter = Backbone.Router.extend({
routes: {
"": "defaultRoute",
"news/:country_code":"updatedRoute"
},
defaultRoute: function () {
console.log("defaultRoute");
var movies = new NewsCollection()
new NewsView({ collection: movies });
movies.fetch();
//setInterval(function(){movies.fetch({success: function(){}});}, 60000);
},
updatedRoute:function (country_code) {
//confused
this.movie = this.movies.get(country_code);
}
})
I need to run the updatedRoute function when that will display a list of news based on cat of country code see below.
http://api.example.com/index.php/news/country/gb/format/json
How do i update the whole feed when a list item is click so the browser url would be.
http://localhost:8888/backbonetut/#news/gb
my list item is.
<li><a href='#news/gb'>GB</a></li>
I can get that in the updateRoute function with
this.movie = this.movies.get(country_code);
Can someone please help
You can either override the fetch function on your collection or temporarily change the url of the collection in your router action.