Backbone DELETE is sent with an empty body - javascript

Delete Function:
My backbone function to delete a model (called on the click of a button) looks like this:
deleteCar: function (ev) {
console.log(this.car.toJSON());
this.car.destroy({
success: function () {
router.navigate('', {trigger:true});
}
});
return false;
},
this.car is created in another function but in the main scope. As seen above, I'm logging the contents of this.car and I get a JSON like this:
Object {carId: "17", carDes: "awesome"}
Now, I'm calling this.car.destroy... and I'm observing the network tab on Chrome. I can see a DELETE request firing but there is no data appended to the request. It's just an empty request to the correct url.
How can I attach my car model to the request?
Edit:
Render Function:
This is the function that creates a new car model. It is in the same Backbone view as the Delete function above.
render: function(options) {
var that = this;
if (options.id) {
that.car = new Car({
carId: options.id
});
that.car.url = 'http://localhost/Project/index.php/rest/resource/car/carId/' + options.id;
that.car.fetch({
success: function(car) {
console.log(that.car.toJSON());
that.car.url = 'http://localhost/Project/index.php/rest/resource/car/';
var template = _.template($("#edit-car-template").html());
var data = {
car: that.car
};
that.$el.html(template(data));
}
});
} else {
var template = _.template($("#edit-car-template").html());
var data = {
car: null
};
that.$el.html(template(data));
}
}
Edit-Car-Template
<script type="text/template" id="edit-car-template">
<form class="edit-car-form">
<legend>
<%= car ? 'Edit' : 'New' %> Car</legend>
<label>Car Description</label>
<input name="carDes" type="text" value="<%= car ? car.get('carDes') : '' %>">
<hr />
<button type="submit" class="btn">
<%= car ? 'Update' : 'Create' %>
</button>
<% if(car) { %>
<input type="hidden" name="carId" value="<%= car.get('carId') %>" />
<button data-car-id="<%= car.get('carId') %>" class="btn btn-danger delete">Delete</button>
<% }; %>
</form>
</script>
Edit 2:
Layout:
The view layout of my application is as follows:
And the following code is used to render the CarListView (get the list of cars using the REST API)
var CarListView = Backbone.View.extend({
el: '.page',
render: function () {
var that = this;
this.cars = new Cars();
this.cars.fetch({
success: function () {
var template = _.template($("#car-list-template").html());
var data = {cars: that.cars.toJSON()};
that.$el.html(template(data));
}
})
}
});
Models
My car model and car collection are defined as follows:
var Car = Backbone.Model.extend({
urlRoot: ROOT + 'car',
idAttribute: 'carId'
});
var Cars = Backbone.Collection.extend({
model: Car,
url: ROOT + 'car'
})
Update Function:
And following is the code for saving (updating) the model once the update button is clicked. This part works perfectly.
events: {
'submit .edit-car-form': 'saveCar',
'click .delete': 'deleteCar'
},
saveCar: function (ev) {
console.log('in save');
var carDetails = $(ev.currentTarget).serializeObject();
var car = new Car();
car.save(carDetails, {
success: function (car) {
router.navigate('', {trigger: true});
}
});
return false;
}

Sounds like this is working as intended. The Backbone.Model.destroy() method will generate an HTTP DELETE call to the model's the relevant URL. It typically won't have any content in the method body, as the ID at the end of the URL should be all you need to delete the RESTful resource. If you need different behavior, Backbone expects you to override the model's sync method (see here and here). Traditionally HTTP servers ignored any body sent on an HTTP DELETE method call, and the HTTP spec doesn't mention it needing a body, so Backbone is just encouraging you to follow that example.
Note also that setting the url property on the model instance itself is not the usual way to ensure the URL has the model ID. If you're going to use a Backbone.Model outside of a Backbone.Collection, you should include the urlRoot property when specifying Car ... where you can also specify the fetch function if you really need to override it:
var Car = Backbone.Model.extend({
urlRoot: '/Project/index.php/rest/resource/car`
fetch: function(options) {
// ... if needed, but note you can provide a "success"
// callback in the options; see below.
}
});
Doing it that way, Backbone will ensure that any call to car.destroy() will generate the right URL. For instance:
var car = new Car({
id: 123
});
// This will GET /Project/index.php/rest/resource/car/123
car.fetch({
success: function() {
console.log('Received: ' + car.toJSON());
// ... anything else you need to do after fetching.
});
});
// ... some time later ...
// This will DELETE /Project/index.php/rest/resource/car/123
car.destroy({
success: function() {
console.log('Car has been deleted on server');
}
});
Again, if your server needs more info than the model's ID to delete something, you'll have to override the sync method... but that's another question!

Related

Knockout.js - Data binding outputting function text when not using parens

I am new to Knockout and have been trying to follow code examples and the documentation, but keep running into an issue. My data bindings printing the Knockout observable function, not the actual values held by my observable fields. I can get the value if I evaluate the field using (), but if you do this you do not get any live data-binding / updates.
Below are some code snippets from my project that are directly related to the issue I am describing:
HTML
<div class="col-xs-6">
<div data-bind="foreach: leftColSocialAPIs">
<div class="social-metric">
<img data-bind="attr: { src: iconPath }" />
<strong data-bind="text: name"></strong>:
<span data-bind="text: totalCount"></span>
</div>
</div>
</div>
Note: leftColSocialAPIs contains an array of SocialAPIs. I can show that code too if needed.
Initializing the totalcount attribute
var SocialAPI = (function (_super) {
__extends(SocialAPI, _super);
function SocialAPI(json) {
_super.call(this, json);
this.totalCount = ko.observable(0);
this.templateName = "social-template";
}
SocialAPI.prototype.querySuccess = function () {
this.isLoaded(true);
appManager.increaseBadgeCount(this.totalCount());
ga('send', 'event', 'API Load', 'API Load - ' + this.name, appManager.getRedactedURL());
};
SocialAPI.prototype.toJSON = function () {
var self = this;
return {
name: self.name,
isActive: self.isActive(),
type: "social"
};
};
return SocialAPI;
})(API);
Updating totalcount attribute for LinkedIn
var LinkedIn = (function (_super) {
__extends(LinkedIn, _super);
function LinkedIn(json) {
json.name = "LinkedIn";
json.iconPath = "/images/icons/linkedin-16x16.png";
_super.call(this, json);
}
LinkedIn.prototype.queryData = function () {
this.isLoaded(false);
this.totalCount(0);
$.get("http://www.linkedin.com/countserv/count/share", { "url": appManager.getURL(), "format": "json" }, this.queryCallback.bind(this), "json").fail(this.queryFail.bind(this));
};
LinkedIn.prototype.queryCallback = function (results) {
if (results != undefined) {
results.count = parseInt(results.count);
this.totalCount(isNaN(results.count) ? 0 : results.count);
}
this.querySuccess();
};
return LinkedIn;
})(SocialAPI);
In the <span data-bind="text: totalCount"></span>, I expect to see a number ranging from 0-Integer.MAX. Instead I see the following:
As you can see, its outputting the knockout function itself, not the value of the function. Every code example I've seen, including those in the official documentation, says that I should be seeing the value, not the function. What am I doing wrong here? I can provide the full application code if needed.
Not sure, but KO view models obviously tend to bind own (not inherited through prototypes) observable properties only. So you should rewrite your code to supply totalCount observable for every social network separately.

Underscore Template not working with Backbone View

I am not sure why my Underscore Template is not rendering. I would like it to show 3 select drop down menus based on the data returned.
Here's a fiddle to my code. Check the console for the data: http://jsfiddle.net/f7v3g/
If you see the data returned you'll see the following structure
-models
--attributes
---dimensions
----object0
-----name (Will be the text label that appears next to the first drop down menu)
-----refinements (children of refinements should be the option tags)
----object1
-----name (Will be the text label that appears next to the second drop down menu)
-----refinements (children of refinements should be the option tags)
----object2
-----name (Will be the text label that appears next to the third drop down menu)
-----refinements (children of refinements should be the option tags)
Here's the Backbone JavaScript:
(function () {
var DimensionsModel = Backbone.Model.extend({
defaults: {
dimensionName : 'undefined',
refinements : 'undefined'
}
});
var DimensionsCollection = Backbone.Collection.extend({
model: DimensionsModel,
url: 'http://jsonstub.com/calltestdata',
});
var setHeader = function (xhr) {
xhr.setRequestHeader('JsonStub-User-Key', '0bb5822a-58f7-41cc-b8a7-17b4a30cd9d7');
xhr.setRequestHeader('JsonStub-Project-Key', '9e508c89-b7ac-400d-b414-b7d0dd35a42a');
};
var DimensionsView = Backbone.View.extend({
el: '.js-container',
initialize: function (options) {
this.listenTo(this.model,'change', this.render);
this.model.fetch({
beforeSend: setHeader
});
console.log(this.model);
return this;
},
render: function () {
this.$el.html( this.template(this.model, 'dimensions-template') );
},
template: function (models, target) {
var templateSelectors = _.template($('#'+target).html(),{
dimensions: this.model
});
return templateSelectors;
},
});
var myCollection = new DimensionsCollection();
var myView = new DimensionsView({model: myCollection});
}());
Here is my HTML and Underscore template:
<div class="js-container">
<script type="text/template" id="dimensions-template">
<% _.each(dimensions, function(dimension,i){ %>
<%- dimension.get('dimensionName') %> <select id="<%- dimension.get('dimensionName') %>">
<option>Select</option>
<% _.each(dimension.get('refinements'), function(ref,x){ %>
<option data-refineurl='{
"refinementUrl": "<%- ref.refinementurl %>",
"nVal": "<%- ref.nval %>"
}'><%- ref.name %></option>
<% }); %>
</select>
<% }); %>
</script>
</div>
Edit: Spelling and example of data scructure.
I see few mistake:
1) inside DimensionsView initialize, you should add a this.render call
2) inside template: function (models, target), you use this.models. but you pass models as first parameter ?
3) Did you add model to your collection somewhere? now you template will try to loop over them. So it need models to loop in the collection.

Showing an Array using JSON from Database in Ember

Well, I guess I am encountering a bit of an issue again here. I will explain what I am trying to do.
I have a teammembers template in which I want to show Team Members & their specific information from a specific team. For that I have to join 3 tables.
This query should give you an idea:
SELECT *
FROM teams_members tm
inner join members m on tm.members_member_id=m.id
inner join teams t on tm.team_team_id=t.id
WHERE
t.team_name='Vancouver Canuck'
What I initially thought that I can make a simple array and simply do pushObject. But It's not working & and moreover, how would I show them?
Here's what I tried:
App.Model = Ember.Object.extend({});
App.TeammembersController = Ember.ObjectController.extend({
teammembers : [], //This is for getTeamMembers Action, Coming as undefined
selectedTeam : null,
team : function() {
var teams = [];
$.ajax({
type : "GET",
url : "http://pioneerdev.us/users/getTeamNames",
success : function(data) {
for (var i = 0; i < data.teams.length; i++) {
var teamNames = data.teams[i];
teams.pushObject(teamNames);
}
}
});
return teams;
}.property(),
actions : {
getTeamMembers : function() {
teamName = this.get('selectedTeam.team_name');
data = {
team_name : this.get('selectedTeam.team_name'),
};
if (!Ember.isEmpty(teamName)) {
$.ajax({
type : "POST",
url : "http://pioneerdev.us/users/getTeamMembers",
data : data,
dataType : "json",
success : function(data) {
for (var i = 0; i < data.teammembers.length; i++) {
var teamNames = data.teammembers[i].firstname;
teammembers.pushObject(teamNames);
}
}
});
return teammembers;
console.log(teammembers);
} else {
}
}
}
});
I am getting teammember array as undefined in this. The snippet in actions will be responsible for spitting out Team Member's information when Team Name is selected from Ember.Select.
Thanks to https://stackoverflow.com/users/59272/christopher-swasey, I was able to re-use my snippet here:
<script type="text/x-handlebars" id="teammembers">
<div class="row">
<div class="span4">
<h4>Your Team Members</h4>
{{view Ember.Select
contentBinding="team"
optionValuePath="content.team_name"
optionLabelPath="content.team_name"
selectionBinding="selectedTeam"
prompt="Please Select a Team"}}
<button class="btn"
{{action 'getTeamMembers' bubbles=false }}>Get Team Members</button>
</div>
</div>
</script>
Moreover, what will user do, he will select the team from Ember.Select & when he clicks the button, somewhere I should be able to spit out team members & their information. In future, I might want to grab ids and delete them from server as well. How would I do that as well?
So, should I use custom views or is there some other way to do this?
There is an issue with the code that populates properties from ajax. For example the code of property team of App.TeammembersController does the following
1.initializes a local array variable teams
2.uses ajax to retrieve asynchronously the data from server
2.1.meanwhile the teams array within the ajax callback gets populated but never returned at the proper state of including data. It is required to set the controller's property once the teams array has been populated with the data. Then ember's binding will take care of the rest (populate controller's property, notify any other object interested, event the template to render the results)
3.and returns the empty teams array
So, you need to add two lines of code as follows,
team : function() {
var teams = [];
var self = this;/*<- */
$.ajax({
type : "GET",
url : "http://pioneerdev.us/users/getTeamNames",
success : function(data) {
for (var i = 0; i < data.teams.length; i++) {
var teamNames = data.teams[i];
teams.pushObject(teamNames);
}
self.set("team",teams);/*<- */
}
});
return teams;
}.property()
The same should happen for the other properties you retrieve from ajax.
EDIT1
Below is an example based on your code. The code has been moved inside the IndexController and the button doing some action has been disabled for simplicity.
http://emberjs.jsbin.com/IbuHAgUB/1/edit
HBS
<script type="text/x-handlebars" data-template-name="index">
<div class="row">
<div class="span4">
<h4>Your Team Members</h4>
{{view Ember.Select
content=teams
optionValuePath="content.team_name"
optionLabelPath="content.team_name"
selection=selectedTeam
prompt="Please Select a Team"}}
<button class="btn"
{{action 'getTeamMembers' bubbles=false }} disabled>Get Team Members</button>
</div>
</div>
selected team:{{selectedTeam.team_name}}
</script>
JS
App = Ember.Application.create();
App.Router.map(function() {
// put your routes here
});
App.Model = Ember.Object.extend({});
App.IndexController = Ember.ObjectController.extend({
test:"lalal",
teammembers : [],
selectedTeam : null,
teams : function() {
//var teams = [];
var self = this;
/*$.ajax({
type : "GET",
url : "http://pioneerdev.us/users/getTeamNames",
success : function(data) {
for (var i = 0; i < data.teams.length; i++) {
var teamNames = data.teams[i];
teams.pushObject(teamNames);
}
}
});*/
setTimeout(function(){
var data = [{team_name:'team1'}, {team_name:'team2'}, {team_name:'team3'}];//this will come from the server with an ajax call i.e. $.ajax({...})
self.set("teams",data);
},1000);//mimic ajax call
return [];
}.property(),
actions : {
getTeamMembers : function() {
teamName = this.get('selectedTeam.team_name');
data = {
team_name : this.get('selectedTeam.team_name')
};
if (!Ember.isEmpty(teamName)) {
/*$.ajax({
type : "POST",
url : "http://pioneerdev.us/users/getTeamMembers",
data : data,
dataType : "json",
success : function(data) {
for (var i = 0; i < data.teammembers.length; i++) {
var teamNames = data.teammembers[i].firstname;
teammembers.pushObject(teamNames);
}
}
});*/
return teammembers;
} else {
}
}
}
});
The same concept can be followed to retrieve any data from the server and modify/delete it as well. Just have in mind that all requests are async and within the callback functions you should update your ember app model/data, then ember bindings do all the magic.
EDIT2
In order to show the team members in a separate view (based on last comments) once the team is selected, either by clicking the button or from another bound property you may request via ajax the members for the selected team id (unless you have already loaded them eagerly) you can render the property of teammembersinside an included view or partial. For instance the same example and when the button is pressed members appear (without logic hardcoded but async lazy loaded data),
http://emberjs.jsbin.com/IbuHAgUB/2/edit
HBS
<script type="text/x-handlebars" data-template-name="_members">
<i>this is a partial for members</i>
{{#each member in teammembers}}<br/>
{{member.firstName}}
{{/each}}
</script>
JS
App.IndexController = Ember.ObjectController.extend({
test:"lalal",
teammembers : [],
selectedTeam : null,
teams : function() {
var self = this;
setTimeout(function(){
var data = [{team_name:'team1'}, {team_name:'team2'}, {team_name:'team3'}];//this will come from the server with an ajax call i.e. $.ajax({...})
self.set("teams",data);
},1000);//mimic ajax call
return [];
}.property(),
actions : {
getTeamMembers : function() {
var self = this;
setTimeout(function(){
var data = [{firstName:'member1'}, {firstName:'member2'}];//this will come from the server with an ajax call i.e. $.ajax({...})
self.set("teammembers",data);
},1000);//mimic ajax call
}
}
});

Backbone.js event doubts

i have to create events using backbone.js.Below is my js code
var Trainee = Backbone.Model.extend();
var TraineeColl = Backbone.Collection.extend({
model: Trainee,
url: 'name.json'
});
var TraineeView = Backbone.View.extend({
el: "#area",
template: _.template($('#areaTemplate').html()),
render: function() {
this.model.each(function(good){
var areaTemplate = this.template(good.toJSON());
$('body').append(areaTemplate);
},this);
return this;
}
});
var good = new TraineeColl();
var traineeView = new TraineeView({model: good});
good.fetch();
good.bind('reset', function () {
$('#myButtons').click(function() {
traineeView.render();
});
});
<div class = "area"></div>
<div class="button" id="myButtons">
<button class="firstbutton" id="newbutton">
Display
</button>
</div>
<script id="areaTemplate" type="text/template">
<div class="name">
<%= name %>
</div>
<div class="eid">
<%= eid %>
</div>
<div class="subdomain">
<%= subdomain %>
</div>
my o/p on clicking display button is
Display // this is a button//
Sinduja
E808514
HPS
Shalini
E808130
HBS
Priya
E808515
HSG
Now from the view i have to bind a change event to the model..the changes in the model must be triggered on the view to display the output on the click of display button.
This isn´t exactly answering your queston but:
if trainee (I've renamed it to trainees) is a collection you should set it using:
new TraineeView({collection: trainees});
Then in render:
this.collection.models.each(function(trainee)
And you propably wan´t to move the call to fetch outside the view, in the router perhaps:
trainees = new TraineeColl();
view = new TraineeView({collection: trainees});
trainees.fetch();
That way your view only listens to the model.
You also should move the bind part to the views initialize method
this.collection.bind('reset', function () {
this.render();
});
Hope this helps.
var TraineeView = Backbone.View.extend({
el: "#area",
initialize : function(options){ // you will get the passed model in
//options.model
var trainee = new TraineeColl();
trainee.fetch();
trainee.bind('reset change', this.render,this); //change will trigger render
// whenever any model in the trainee collection changes or is modified
}
template: _.template($('#areaTemplate').html()),
render: function() {
this.model.each(function(trainee){
var areaTemplate = this.template(trainee.toJSON());
$('body').append(areaTemplate);
},this);
return this;
}
});
var traineeView = new TraineeView({model: trainee});
});

Backbone Collection Cant Find Model's View Render

I'm trying to render a simple collection view and having a weird issue.
The problem is that when i try to call the render method of the model in a collection's view it can't find the render method.
My Model And View
var PersonModel = Backbone.Model.extend({});
var PersonView = Backbone.View.extend({
tagName : "person",
events:{
"click h3":"alertStatus"
},
initialize:function(){
this.model.on('change',this.render,this);
} ,
render:function(){
var underscore_template = _.template('<h3>Name : <%= name %></h3>'+
'<h3>Last Name : <%= surname %></h3>' +
'<h3>Email : <%= email %> </h3>') ;
console.log("Person View Render Oldu");
this.$el.html(underscore_template(this.model.toJSON()));
},
alertStatus :function(e){
alert("Clicked on Model View");
}
});
My Collection And Collection View
var PersonList = Backbone.Collection.extend({
model:PersonModel,
url:'/models'
});
var personList = new PersonList();
var PersonListView = Backbone.View.extend({
tagName : "personlist",
render : function(){
this.collection.forEach(this.addOne,this);
},
addOne : function(personItem){
var personView = new PersonView({model:personItem});
this.$el.append(personView.render().el); // The call to personView.render throws undefined
},
initialize : function(){
this.collection.on('add',this.addOne,this);
this.collection.on('reset',this.addAll,this);
},
addAll : function(){
this.collection.forEach(this.addOne,this);
}
});
var personListView = new PersonListView({
collection:personList
});
personList.fetch({
success:function(){
console.log("Fetch success");
}
});
I'm calling this JS on document ready with Jquery and adding it to a div with id named app.
My fetch is also successful.The problem persists at the addOne function of the Collection View when trying to call personView.render().el
Any help would be appreciated.
You forgot returning the element in your render:
render : function() {
var underscore_template = _.template('<h3>Name : <%= name %></h3>'+
'<h3>Last Name : <%= surname %></h3>' +
'<h3>Email : <%= email %> </h3>') ;
console.log("Person View Render Oldu");
this.$el.html(underscore_template(this.model.toJSON()));
return this; // chaining
}
Otherwise you can't chain it and you can't access el afterwards.

Categories