I am trying to fetch a JSON on OnChange event. And making changes to the existing haml page.
My aim is to populate another select field with the json values. At the moment I am just trying to print a message that json was fetched. But I get no change in the html.
In the network tab of the console, I see that the URL request is being made, and a 304 response is returned. I can also see the json in the response.
events:
"submit form" : "onSubmit"
"change [name=repository]" : "onChange"
onChange: (e) ->
e.preventDefault()
name = #$("[name=repository]").val()
localStorage['new_issue_last_repo'] = name
token = localStorage['oauth2_github']['accessToken']
#model = new Assignees(name)
console.log 'Printttttt'
#model.fetch {headers : #token},
success: (model) =>
#$('.assignee').html("<span>Fetched assignees</span>")
error: =>
#$('.assignee').html("<span>Failed to fetch assignees :(</span>")
The haml file looks like this.
.message
.assignee
%form
%section.repo-select
%select{name: 'repository'}
- for repository in #repositories.models
- full_name = repository.get('full_name')
- if localStorage['new_issue_last_repo'] == repository.get('full_name')
%option{value: full_name, selected: 'selected'}= repository.get('full_name')
- else
%option{value: full_name}= repository.get('full_name')
How can I get the .assignee to change once the json is fetched. Also how can I access the json data?
I have a similar function that works. I dont know what I am doing wrong in the onChange function.
onSubmit: (e) ->
e.preventDefault()
name = #$("[name=repository]").val()
localStorage['new_issue_last_repo'] = name
repository = #repositories.find (r) -> r.get('full_name') == name
model = new IssueModel({
body: #$("[name=body]").val()
title: #$("[name=title]").val()
assignee: #$("[name=assignee]").val()
milestone: #$("[name=milestone]").val()
}, {repository: repository})
model.save {},
success: (model) =>
#badge = new Badge()
#badge.addIssues(1)
#$('.message').html("<span>Issue ##{model.get('number')} was created!</span>")
error: =>
#$('.message').html("<span>Failed to create issue :(</span>")
I'm not that big on HAML but this:
%form
%section.repo-select
%select{name: 'repository'}
should become this HTML:
<form>
<section class="repo-select">
<select name="repository">
<!-- ... -->
</select>
</section>
</form>
right? That means that there is nothing that will match the ID-selector #repo-select so of course the handler bound to those events, onChange, will never be called.
If you want to get change-events from that <select>, then you'll want something like this in your events:
'change [name=repository]'
See Backbone's View#delegateEvents and jQuery's Selectors document for details.
As far as your messages go, I think you're a little confused about the difference between the Model#save arguments:
save model.save([attributes], [options])
and the Model#fetch arguments:
fetch model.save([options])
save takes two arguments with the callbacks in the second so this works:
model.save {},
success: (model) => ...
error: => ...
but fetch only takes one argument and the callbacks should be in that argument so this:
#model.fetch {headers : #token},
success: (model) => ...
error: => ...
won't work as fetch won't even see the success or error callbacks. You'd want to say this:
#model.fetch
headers: #token
success: (model) => ...
error: => ...
to get all three arguments to fetch.
Related
I'm creating a form using Vue JS (more specifically the Vuetify library) and when clicking the 'Add' button I am trying to make it so that the user input is added to the database.
The database has 3 columns: id, type_id, value. I want to link the user input to the value column.
Note that allDesserts is an array that stores all of the items in the database. This is what I want to add to.
How can I achieve this?
Component in my form:
<v-combobox
:items="allDesserts.map(a => a.value)"
label="Project Type"
:search-input.sync="search"
>
<template v-slot:no-data>
<v-text-field
label="Add new dessert"
v-model="search"
>
</v-text-field>
<v-btn
#click="enterKey"
>Add</v-btn>
</template>
</v-combobox>
Axios request/method:
enterKey () {
axios.post('/api/desserts', {
value: 'key'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error.response);
});
}
My controller:
public function storeDessert(Request $request)
{
$dropdownType = new DropdownType();
$dropdownType->attribute_id = $request->input(rand(1, 10000));
$dropdownType->value = $request->input('value');
$dropdownType->save();
}
I am getting the following error:
"Illegal string offset 'id'"
I think your error is on this line.
$dropdownType->attribute_id = $request->input(rand(1, 10000));
Let say rand(1, 10000) will give you a value of 100, now you used this 100, as a key to access value in your requests which is not available.
Try to look your payload. You are just passing a data which has a key value only, this one.
{value: 'key'}
and now this line will work cause it is available in your payload.
$dropdownType->value = $request->input('value');
But not this one.
$dropdownType->attribute_id = $request->input(rand(1, 10000));
I have a Sitesand a Positionscollection. Each time the user selects a new site, the id is sent to the refreshPositions method which is in charge of doing the fetch call.
The route to get the positions look like this '.../sites/1/positions'
view.js
refreshPositions: function(siteId) {
this._positions.fetch({
success: this.onPositionsFetchSuccess.bind(this),
error: this.onPositionsFetchError.bind(this)
});
},
So refreshPositions is called whenever I need to update the positionson the page and the siteId parameter has the id, I just don't know to tell fetch to route to something like .../sites/n/positions where n would be the siteId .
Sorry if I missed relevant informations for my question, I'm pretty new to backbone.
I see, so you are calling fetch from your Positions Collection. The out-of-the-box functionality there is to fetch the whole collection (every Position object) if you have a RESTfull api set up. If you want more specific behaviour from your collection, you can probably write it into the Collection object definition.
var PositionCollection = Backbone.Collection.extend({
initialize: function(models, options) {
this.siteId = (options && options.siteId) || 0;
},
url: function() {
if (!this.siteId) {
return '/positions'; // or whatever
}
return '/sites/' + this.siteId + '/positions';
},
// etc...
});
Then, assuming that _positions refers to an instance of PositionCollection you can do:
refreshPositions: function(siteId) {
this._positions.siteId = siteId; // or wrap in a setter if you prefer
this._positions.fetch({
success: this.onPositionsFetchSuccess.bind(this),
error: this.onPositionsFetchError.bind(this)
});
},
I've got two types of docs in pouchdb:
todos - list of todos
user - just user number put in pochdb by separate form
When I write todos I also have variable for userNo. This way I know which todos he owns.
I've got two functions in provider to get todos, and user number.
In html list I want to filter todos by user number through pipe:
<ion-item-sliding *ngFor="let todo of todos | filter : 'numer_p' : this.todoService.userNo">
If I enter this number by hand it works great. Todos are filtered by this number.
The problem is that I have two calls in home.ts ionViewLoaded:
//call provider to get all docs to show on the list
this.todoService.getTodos().then((data) => {
this.todos = data;
});
//call provider to get userNo from pouchdb and set variable in the provider
this.todoService.getUser().then((result) => {
console.log("getBadacz result:" + JSON.stringify(result));
this.todoService.userNo = result['name'];
}).then(function(second){;
console.log("second");
});
I need to call getTodos AFTER getUser. So I need to run this functions in sequence using Promises.
Without it this.todoService.userNo in filter is undefined, because it is not set yet. And it will not work.
I tried to do it like this:
this.todoService.getUser().then((result) => {
console.log("getBadacz result:" + JSON.stringify(result));
this.todoService.userNo = result['name'];
}).then(function(second){;
console.log("second");
this.todoService.getTodos().then((data) => {
this.todos = data;
});
});
But there is an error:
EXCEPTION: Error: Uncaught (in promise): TypeError: Cannot read property 'todoService' of null
I tried to arrange this promises in sequence but without success.
Here is fiddle where you can find implementation of functions in provider:
Filter pouchdb docs by userID saved in another doc
Thank you very much for your help.
In situation like this, I would try to include userId in the todo key, that would increase performance (a todos document may have key like this userId_todoId).
So you will not need two promises at all.
I want to fire fetch method on Backbone Collection which would pass an Id parameter similar to what happens in Model.fetch(id)
E.g.
var someFoo= new Foo({id: '1234'});// Where Foo is a Backbone Model
someFoo.fetch();
My Backbone collection:-
var tasks = backbone.Collection.extend({
model: taskModel,
url: '/MyController/GetTasks',
initialize: function () {
return this;
}
});
In my View when I try to fetch data:-
var _dummyId = 10; //
// Tried approach 1 && It calls an api without any `id` parameter, so I get 500 (Internal Server Error).
this.collection.fetch(_dummyId);
// Tried approach 2 && which fires API call passing Id, but just after that
// I am getting error as below:- Uncaught TypeError: object is not a function
this.collection.fetch({
data: {
id: _dummyId
}
});
Found it very late : To cut short the above story I want something like Get /collection/id in backbone.
Thank you for your answers, finally I got the solution from Backbone.js collection options.
Apologies that I couldn't explain the question properly while for same requirement others have done brilliantly and smartly.
Solution : I can have something like :-
var Messages = Backbone.Collection.extend({
initialize: function(models, options) {
this.id = options.id;
},
url: function() {
return '/messages/' + this.id;
},
model: Message,
});
var collection = new Messages([], { id: 2 });
collection.fetch();
Thanks to nrabinowitz. Link to the Answer
As mentioned by Matt Ball, the question doesn't make sense: either you call fetch() on a Collection to retrieve all the Models from the Server, or you call fetch() on a Model with an ID to retrieve only this one.
Now, if for some reason you'd need to pass extra parameters to a Collection.fetch() (such as paging information), you could always add a 'data' key in your options object, and it may happen that one of this key be an id (+add option to add this fetched model rather than replace the collection with just one model)... but that would be a very round-about way of fetching a model. The expected way is to create a new Model with the id and fetch it:
this.collection = new taskCollection();
newTask = this.collection.add({id: 15002});
newTask.fetch();
In your code however, I don't see where the ID is coming from, so I am wondering what did you expect to be in the 'ID' parameter that you wanted the collection.fetch() to send?
I have a recipe model, and a recipe has an ingredientlist collection which stores a bunch of ingredients.
When I add an ingredient to the ingredient list from a form submit, I have to get an 'id' from the server, so I do an ajax request, get the id, and am trying to then add the ingredient to the model.
In my ingredientlist.view, I have
initialize: function(){
this.recipe = this.model;
},
get_ingredient: function(ingredient){
var ingredient_id = new MyApp.Models.Ingredient;
ingredient.url='/ingredients/?ing='+encodeURIComponent(ingredient_array[i]);
ingredient.fetch({
success: function() {
this.recipe('add:ingredients', function(ingredient,ingredientlist){
});
},
error: function() {
new Error({ message: "adding ingredient" });
}
});
}
I didn't include the function which triggers the 'get_ingredient', because it I am getting the ajax fine, so the problem isn't in triggering the 'get_ingredient'.
I get the errorUncaught TypeError: Property 'recipe' of object [object DOMWindow] is not a function
using the existing code.
what is the best way to accomplish something like this?
First of All i'm a newbie too with backbone.js!
So my thoughts is :
U need to bind your get_ingredient in your View : look bind to trigger your functions!
Try to pass the Context (this) to "get_ingredients"
This is just my 5 cents