how to get data from server in backbone - backbone.js

I am creating an app in backbone. This current code works but now I want to get the data from the server. My method at /myfriends/getData returns a json of friends name and etc.
How can I make this code to get that json from the server. I read up a little and they are using routes etc…I just need to use it on one page of my app so I do not want to do a lot of routing etc
thanks
$(function() {
FriendList = Backbone.Collection.extend({
    initialize: function(){
        this.bind("add", function( model ){
            alert("hey");
            view.render( model );
        })
    }
});
FriendView = Backbone.View.extend({
    tagName: 'li',
    events: {
        'click #add-input':  'getFriend',
    },
    initialize: function() {
        this.friendslist = new FriendList;
        _.bindAll(this, 'render');
    },
    getFriend: function() {
        var friend_name = $('#input').val();
        this.friendslist.add( {name: friend_name} );
    },
    render: function( model ) {
        $("#friends-list").append("<li>"+ model.get("name")+"</li>");
        console.log('rendered')
    },
});
var view = new FriendView({el: 'body'});
});
here is a working copy
http://jsfiddle.net/thomas/Yqk5A/
thanks
TIRED
this is what I have to show the data and tried after the suggestion and still no luck
$(function() {
FriendList = Backbone.Collection.extend({
    initialize: function(){
        this.bind("add", function( model ){
            alert("hey");
            view.render( model );
        })
    }
});
FriendsServer = new Backbone.Collection({
initialize: function(){
url : '/friends/Data',
this.bind("test", function( model ){
view.render( model );
})
}
});
FriendView = Backbone.View.extend({
    tagName: 'li',
    events: {
        'click #add-input':  'getFriend',
    },
    initialize: function() {
        this.friendslist = new FriendList;
        _.bindAll(this, 'render');
    },
    getFriend: function() {
        var friend_name = $('#input').val();
        this.friendslist.add( {name: friend_name} );
    },
    render: function( model ) {
        $("#friends-list").append("<li>"+ model.get("name")+"</li>");
        console.log('rendered')
    },
});
FriendsServerView = Backbone.View.extend({
tagName: 'div',
render: function( model ){
$("#jsonData").html(FriendServer.fetch);
}
});
var view = new FriendView({el: 'body'});
var view = new FriendsServerView({el: 'body'});
});
in my html I have a div to populate with json data

You just set the url property of your collection and call .fetch() on your collection to load the data from your server. More info at:
http://backbonejs.org/#Collection-fetch
Also, I would bind your model/collection events to your view, not to the model/collection.

Related

AssureData custom filter in angular

How to include custom filter in the code?
This is my service file. I need to filter by name. Also I need to give validations in html for save and cancel using pristine
app.factory('CrusdService', function($http) {
return {
fetchAll: function() {
return $http.get('https:\\localHost:5000\countries').then(
function(response) {
return response.data.data; // depends on the response data.Sometimes it will be response.data.data.data
},
function(error) {
return error;
}
);
},
add: function(data) {
return $http.post('https:\\localHost:5000\country', data).then(
function(response) {
return response;
},
function(error) {
console.log('error');
}
);
},
update: function(data) {
var name = {
"name": data.name
};
return $http.put('https:\\localHost:5000\country' + data._id, name).then(
function(response) {
return response;
},
function(error) {
console.log('error');
}
);
},
activate: function(id) {
return $http.put('https:\\localHost:5000\country' + id + '\activate').then(
function(response) {
return response;
},
function(error) {
console.log('error');
}
);
},
deactivate: function(id) {
return $http.put('https:\\localHost:5000\country' + id + '\deactivate').then(
function(response) {
return response;
},
function(error) {
console.log('error');
}
);
}
}
});
in html file add the following content:
For the search field give the ng-model="searchValue"
In ng-repeat = "data in country |.. | filter:searchValue"
app.filter("customSearch",function(){
  return function(data,search){
    var filtered = [];
            if(!!search){
              for(var i=0;i<data.length;i++){
               if(data[i].country.toLowerCase().indexOf(search) !== -1){
                  filtered.push(data[i]);
               }
              }
            }
            else{
             filtered = data;
            }
            return filtered
  }
})
In html file add the following content:
For the search field give the ng-model="searchValue"
In ng-repeat = "data in country |.. | filter:searchValue"
app.filter("customSearch",function(){
  return function(data,search){
    var filtered = [];
            if(!!search){
              for(var i=0;i<data.length;i++){
               if(data[i].country.toLowerCase().indexOf(search) !== -1){
                  filtered.push(data[i]);
               }
              }
            }
            else{
             filtered = data;
            }
            return filtered
  }
})
in html file add the following content:
<span class="error" ng-if="formname.inputname.$invalid">enter correct data</span> //add this below the save button
for disbaling save and update button in pop up
save - ng-disabled="formname.inputname.$invalid || formname.inputname.$pristine" //formname is the name of the form and inputname is name of the button. if button name is not there add one.
update - ng-disabled="formname.inputname.$invalid || formname.inputname.$pristine"
-----
ng-model="searchString" ng-change="search(searchString)">
$scope.search = function(searchValue) {
$scope.list = ($filter("filter")($scope.searchList, {name: searchValue}));
};
HTML
<div class="form-group" ng-class="{'has-error': dataForm.country.$invalid && dataForm.country.$dirty}">
<input type="text" ng-model="country" name="country" class="form-control" required>
<span class="error text-danger" ng-show="dataForm.country.$invalid && dataForm.country.$dirty">Required</span>
<input type="submit" value="Submit" ng-disabled="dataForm.$invalid">
</div>

Changing state does not trigger render

I'm having a small issue with a component implementation.
Find the code below
var AroundMe = React.createClass({
getInitialState: function(){
return({
dances: [],
events: this.props.events,
user_coords: {}
})
},
update_events: function(data){
this.setState({events: data});
},
filter_by_geolocation: function(){
var vm = this;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position){
vm.setState({user_coords: {longitude: position.coords.longitude, latitude: position.coords.latitude}});
$.ajax({
url: "/aroundme.json",
datatype: 'JSON',
data: vm.state.user_coords,
method: 'GET'
}).done(function(response){
vm.update_events(response.aroundme);
}.bind(vm));
});
} else {
console.log("geo not supported")
}
},
render: function() {
return(
<div>
<button onClick={this.filter_by_geolocation} className='btn btn-danger'>Locate me</button>
<EventsList events={this.state.events} />
</div>
);
}
});
Clicking on the button changes the events state but does not send the new value to to the Eventslist component.
What did I do wrong?
Thanks for your help!
cheers
I have a hunch. setState is asynchronous so you need to use a callback.
Change this:
vm.setState({user_coords: {longitude: position.coords.longitude, latitude: position.coords.latitude}});
$.ajax({
url: "/aroundme.json",
datatype: 'JSON',
data: vm.state.user_coords,
method: 'GET'
}).done(function(response){
vm.update_events(response.aroundme);
}.bind(vm));
To this:
vm.setState({user_coords: {longitude: position.coords.longitude, latitude: position.coords.latitude}}, function() {
$.ajax({
url: "/aroundme.json",
datatype: 'JSON',
data: vm.state.user_coords,
method: 'GET'
}).done(function(response){
vm.update_events(response.aroundme);
}.bind(vm));
});

Angular resource custom post method

I need to post data to a SharePoint list, and I want to clean up my code by using
a resource factory, until now I have posted data like this:
this.save = function(data) {
data["__metadata"] = { "type": getItemTypeForListName('ListName') };
var restQueryUrl = appweburl + "/_api/lists/getByTitle('ListName')/items";
$.ajax({
url: restQueryUrl,
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
},
data: JSON.stringify(data),
success: function (data) {
console.log(data);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
};
And so far my resource factory looks like this:
myApp.factory('Entry', function($resource) {
return $resource(appweburl + "/_api/lists/getByTitle('ListName')/items", {}, {
get: {
method: 'GET',
headers: { "Accept": "application/json; odata=verbose" },
url: appweburl + "/_api/lists/getByTitle('ListName')/items?$select=Id,Title,Description&$filter=ID eq :ID"
},
query: {
method: 'GET',
headers: { "Accept": "application/json; odata=verbose" },
url: appweburl + "/_api/lists/getByTitle('ListName')/items?$select=Id,Title,Description"
}
})
});
How can I 'convert' my save function to a resource method?
Okey, so I was easier than I thought, what I had to do was run the function 'getItemTypeForListName' before calling the save function, this adds the metadata needed to save to sharepoint. And in my resource factory add this:
save: {
method: 'POST',
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
}
}
And then in my controller call it like this:
$scope.test = new Entry();
$scope.test.Title = 'testTitle';
// function to set metadata
$scope.test["__metadata"] = { "type": getItemTypeForListName('ListName') };
Entry.save($scope.test);

Chrome app angular js not working

I am building a chrome application and have used angularjs in some parts. The script works fine on a web browser but when i use it in my app it does not. Even the controller function is not being invoked.
In my html file i've included the following code
<div name="teaminfo" ng-controller="teamsController">
    <table>
        <thead>
            <th>TeamName</th>
            <th>Wins</th>
        </thead>
        <tr ng-repeat="team in teams">
            <td>
                <input type="text" ng-model="team.teamName">
            </td>
            <td>
                <input type="text" ng-model="team.w">
            </td>
        </tr>
    </table>
    <button class="submit" ng-click="savedata();" type="submit">Save new values</button>
</div>
and the javascript
var teamsController = function ($scope, $http) {
$http.get("teams.json").success(function (data) {
$scope.teams = data.teams;
console.log(data);
console.log($scope.teams);
});
$scope.savedata = function () {
console.log("savedata function");
teams = angular.copy($scope.teams);
console.log(teams);
}
}
have you enabled javascript in your java code
webview.getSettings().setJavaScriptEnabled(true);

jsonp return number

Hi in my succes function im trying to return 6 numbers from my callback jsonp function and pass to a var, something like; im out of ideas thnx P
for (var bw=0; bw < bw_numbers.length; x++) {
$('#_pnl' + bw).innerHTML = bw_numbers[bw];
}
jsonCallback(
   {
"bw_numbers": [10, 12, 15, 24, 27, 41]
}
);
var url = 'http://www.blabla.com/ajax/bw_results_latest.json?callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
//do my array thing!!!!
},
error: function(e) {
alert(e.message);
}
});
you need to write the jsonCallBack function
$.ajax({
type: 'GET',
url: url,
async: false,
contentType: "application/json",
dataType: 'jsonp',
error: function(e) {
alert(e.message);
}
});
function jsonCallBack(data)
{ alert(data); }
If you return like
jsonCallback([10, 12, 15, 24, 27, 41])
you can access it as array from javascript
I got it now, I wasnt sure if the json data was able to be used as an array, it is and here is code! Thanks P
var url = 'http://www.blabla.com/ajax/results_latest.json?callback=?';
$.ajax({
type: 'GET',
url: url,
processData: true,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function (data) {
processData(data);
}
});
function processData(data){
for (var x=0; x < data.bw_numbers.length; x++) {
document.getElementById('_pnl' + x).innerHTML = data.bw_numbers[x];
}
}

Resources