Confused with Backbone.js Paginator - javascript

I am trying to introduce pagination using the backbone.js paginator plugin's requestPager.
Problem: After setting up the collection which extends Backbone.Paginator.requestPager, I refreshed the webpage and the javascript console threw the error:
Uncaught TypeError: Object function (a){return new m(a)} has no method 'result' backbone.paginator.js:678
I am very new to backbone and is not sure what went wrong. Is it because I used fetch(), which showed up in the screenshot of the error below? I also noticed that no GET requests were sent to the backend. What happened, and how should I fix this? Thanks!
JS code
// Collection
window.ListingCollection = Backbone.Paginator.requestPager.extend({
model: Listing,
paginator_core: {
type: 'GET',
dataType: 'jsonp',
url: 'api/listings'
},
paginator_ui: {
firstPage: 0,
currentPage: 0,
perPage: 10,
totalPages: 10
},
server_api: {
'$filter': '',
'$per_page': function() { return this.perPage; },
'$current_row': function() { return this.currentPage * this.perPage; },
'$order_by': 'listing_id'
},
parse: function(response){
this.totalPages = Math.floor(response.total_rows / this.perPage);
}
});
JS Code
// Router
var AppRouter = Backbone.Router.extend({
routes: {
'': 'listings',
'listings': 'listings'
},
listings: function() {
var self = this;
// Load initial search results
this.listingList = new ListingCollection();
this.listingList.fetch({
success: function() {
self.listingListView = new ListingListView({ model: self.listingList });
$('#listing_list table').append(self.listingListView.render().el);
}
});
this.listingFilterView = new ListingFilterView();
}
});
Screenshot of Error in Javascript Console
JS Includes
<!-- JavaScript -->
<script src="assets/js/lib/jquery-1.7.1.min.js"></script>
<script src="assets/js/lib/underscore-min.js"></script>
<script src="assets/js/lib/backbone-min.js"></script>
<script src="assets/js/lib/backbone.paginator.js"></script>
<script src="assets/js/lib/bootstrap.js"></script>
<script src="assets/js/lib/bootstrap-datepicker.js"></script>
<script src="assets/js/app.js"></script>

You are probably using older version of Underscore. I use 1.3.1 and it does not have result() method. Download their new production version 1.3.3 - it has result().

Related

Laravel 5.5 + Vue.js 2.x Proper API requests

I am working locally on a Laravel 5.5 project which uses Vue.js 2.5.9 on with XAMP Server.
I have to load some information to the DOM and refresh it when click "Refresh" button.
Sometimes the information is loaded and well displayed but sometimes they are not (some of the responses are):
Error 429: { "message": "Too Many Attempts." }
Error 500: { "message": "Server Error." }
I managed to "solve" the first issue (error 429) by increasing the Middleware throttle in Kernel.php from 'throttle:60,1', to 100,1)
But the second error I am not sure why I am get it sometimes and sometimes not.
I have this in my APIController (for example):
public function users()
{
$users = User::all();
return response()->json($users);
}
Then in app.js I call the methods in the created hook like this:
const app = new Vue({
el: '#app',
data: {
...
totalUsers: 0,
...
},
created: function() {
...
this.loadUsers();
...
},
methods: {
...
loadUsers: function() {
axios.get('/api/admin/users')
.then(function (response) {
app.totalUsers = response.data.length;
});
},
refreshData: function() {
this.loadUsers():
},
...
}
});
Maybe should I replace $users = User::all() to $users = User::count() to avoid loading "too much data" in API requests?
I think you should be using mounted() instead of created() in your vue.
const app = new Vue({
el: '#app',
data: {
...
totalUsers: 0,
...
},
mounted: function() {
...
this.loadUsers();
...
},
methods: {
...
loadUsers: function() {
axios.get('/api/admin/users')
.then(function (response) {
app.totalUsers = response.data.length;
});
},
refreshData: function() {
this.loadUsers():
},
...
}
});
that's the equivalent of the $(document).on(ready) in jQuery. Thats the method that fires when the window has fully loaded.
On a side note, Laravel knows when it is returning json as an ajax response, so you could probably just amend you controller method to this
public function users()
{
return User::all();
}

Vue JS Reload Button not working (v-on:click)

After struggling hours to implement a simple AJAX Call, I am now struggling with a reload button. As far as I can see the syntax is v-on:click="functionName".
In my case the Method I want to use is fetchData so -> v-on:click="fetchData".
However it does Nothing.
This is my vue Code:
<script>
var url = '{{ route('getAllFiles') }}';
new Vue({
el: '#fileTable',
data: {
files: [],
filesAreReady: false
},
created: function(){
this.fetchData();
},
methods: {
fetchData: function(){
var self = this;
self.filesAreReady = false;
self.files = [];
$.get(url, function(data){
self.files = $.parseJSON(data);
self.filesAreReady = true;
});
}
}
});
</script>
This is what PhpStorm tells me about v-on:
I'm using the latest version of Vue through the UNPKG.com CDN.

Backbone targetModel = undefined

I am running into this issue with backbone where the model seems to be undefined to backbone, though all scripts are loaded.
(I am using require to load backbone and other javascript files).
So whenever I do a collection.fetch I get this error in firebug:
TypeError: targetModel is undefined
When I run the script it holds at this point:
if (attrs instanceof Model) {
id = model = attrs;
} else {
id = attrs[targetModel.prototype.idAttribute];
}
when I hover with my mouse over targetModel it says: undefined
It somehow doesn't seem to work now and the only thing I did was changing my html template, which only get loaded after the collection.fetch.
Can you please help me out here?
Here is my model:
var OF = OF || {};
OF.UsersMdl = Backbone.Model.extend({
default: {
username: '',
mailinglist: '',
email: ''
},
initialize: function() {
//
},
result: {
success: false,
message: ''
},
validate: function(att) {
}
});
Here is the collection:
var OF = OF || {};
OF.UsersCollection = Backbone.Collection.extend({
initialize: function() {
//
},
parse: function(data){
return data["all-users"];
},
model: OF.UsersMdl,
url: 'php/api/users'
});
And last but not least the router with the require part:
goToUsers: function() {
require(['./models/users', './views/users_view', './collections/user_collection'], function(UsersMdl, UsersView, UsersCollection) {
OF.usersMdl = new OF.UsersMdl;
OF.usersCollection = new OF.UsersCollection;
OF.usersView = new OF.UsersView;
//when the collection is fetched
$.when(OF.usersCollection.fetch({
data: {
"admin": OF.login.attributes.admin,
"session": OF.login.attributes.session
},
success: function(){
//console.log(OF.usersCollection.length);
}
//then render the view
})).then(function(){
OF.usersView.render();
}, 300);
});
},
Here is the JSON which will be retreived by the fetch:
{
"all-users":
[
{
"username":"tester",
"mailinglist":"1",
"email":"tester#tester.test"
},
{
"username":"tester2",
"mailinglist":"1",
"email":"tester2#tester.test"
},
{
"username":"tester3",
"mailinglist":"0",
"email":"tester3#tester.test"
}
]
}
Thanks in advance
I had this same error and banged my head against it for quite a while because backbone is new to me and this was compounding a fetch issue. Anyhow, I eventually figured out that order matters. Doh! (Less obvious when using CoffeeScript and "class" statements I thinks.) With one of my models I was setting the Collection before the Model (thanks to bad example code from the Backbone.js on Rails book). I reversed that and this error went away to reveal my true fetch issue.
Similarly, your model: property may be invalid for this reason or another reason, leaving it undefined when attempting to reference later.
Side note: I had a similar error in Backbone 1.0.0. When I upgraded to Backbone 1.1.0 I then got this exact error at the same point in backbone code.

Backbone Boilerplate - fetch method don't refresh collection

is my first question here, so I please about some patience and forgive my english:)
When I type link in browser address bar, all is OK. But when I do this inside browser by clicking element, collection is empty. But the main problem is there is always the same response from server, but fetch "dont load" any items, so view render empty collection.
I use Backbone Boilerplate,
Browser.Views.Catalog - it is Backbone.View
Browser.Catalog - it is of Backbone.Collection
My router:
var Router = Backbone.Router.extend({
routes: {
'' : 'browse'
},
refreshCatalog: function(folder){
app.layout.setViews({
"#catalog" : new Browser.Views.Catalog({
collection: app.catalog
})
}).render();
},
browse: function(folder){
app.catalog = new Browser.Catalog();
app.folders.fetch({
error: function() { console.log(arguments); },
success: this.refreshFolders(folder),
data: $.param({folder: folder}),
cache:false
});
//app.catalog = new Browser.Catalog();
app.catalog.fetch({
error: function() { console.log(arguments); },
success: this.refreshCatalog(folder),
data: $.param({folder: folder}),
cache:false
});
},
I belive you should set the catalog in the initialize function
app.catalog = new Browser.Catalog();
should go in here ( add this function)
initialize: function (options) {
app.catalog = new Browser.Catalog();
}
the initialize function is called when the page is loaded so when browsing to #catelog it will have been set http://backbonejs.org/#Router-constructor

backbonejs fetch returns twice (fail, then success)

I am calling my api which returns a task object via json (example return json below):
[{"pkTaskId":"96","fldName":"Change page to template","fldStatus":"Assigned","fldNotes":"http:\/\/williamsconcepts.com\/ci\/codeigniter\/libraries\/template\/reference.html\r\n\r\n111","fldDateDue":"0000-00-00 00:00:00","fldDateCompleted":"0000-00-00 00:00:00"},{"pkTaskId":"103","fldName":"fix list creation","fldStatus":"Assigned","fldNotes":"for some reason there is an SQL syntax error\r\n\r\nok","fldDateDue":"0000-00-00 00:00:00","fldDateCompleted":"0000-00-00 00:00:00"},{"pkTaskId":"104","fldName":"navicat db admin tool","fldStatus":"Assigned","fldNotes":"Try this out:\nhttp:\/\/www.navicat.com\/download\/download.html","fldDateDue":"0000-00-00 00:00:00","fldDateCompleted":"0000-00-00 00:00:00"},{"pkTaskId":"105","fldName":"Styling dropdowns","fldStatus":"Assigned","fldNotes":"Link:\nhttp:\/\/jqueryui.com\/demos\/autocomplete\/#combobox","fldDateDue":"0000-00-00 00:00:00","fldDateCompleted":"0000-00-00 00:00:00"},{"pkTaskId":"147","fldName":"api create task","fldStatus":"Assigned","fldNotes":"","fldDateDue":"0000-00-00 00:00:00","fldDateCompleted":"0000-00-00 00:00:00"}]
$(function(){
window.Task = Backbone.Model.extend({});
window.TaskList = Backbone.Collection.extend({
model: Task,
url: "http://localhost/tasker/index.php/api/tasks/username/lucasmp"
});
window.tasks = new TaskList();
window.AppView = Backbone.View.extend({
initialize: function() {
tasks.fetch({
success: function() {
console.log(tasks.toJSON());
}
});
}
});
window.App = new AppView;
});
$('#fetch').click(function(){
tasks.fetch({
success: function() {
alert("success");
console.log(tasks.toJSON());
},
error: alert("error")
});
});
I'm having an issue though with my fetch.click occurring twice; Once returns fetch error, then returns fetch success. What could be causing this to be fired twice?
Pls try this
error: function(){alert("error")}

Categories

Resources