Question

I am very new to backbone and I am having a bit of trouble.

So I am trying to get some data from a Model within a Collection and I cannot work out how, I am unsure if I have setup my collection incorrectly or something, but that's where I am hoping you guys can help.

Here is my code:

var currentPage = 1;

var Page = Backbone.Model.extend({
    defaults: {
        pageName: '',
        pageID: 0,
        ajaxUrl: '',
        pageUrl: '',
        hashUrl: '',
        previousPage: '',
        nextPage: ''
    }
});

var home = new Page({
    pageName: 'Home',
    pageID: 1,
    ajaxUrl: 'ajax-content/index.html',
    pageUrl: 'index.html',
    hashUrl: '#index',
    previousPage: 'Contact',
    nextPage: 'Our Approach'
});

var WebsitePages = Backbone.Collection.extend({
    model: Page
})

var myWebsite = new WebsitePages([home]);

var ContainerView = Backbone.View.extend({
    el: "body",
    events: {
        'click .previous-page': 'loadPreviousPage',
        'click .next-page': 'loadNextPage'
    },
    loadPreviousPage: function(e) {
        e.preventDefault();

        var pageModel = myWebsite.where({pageID: currentPage});
    },
    loadNextPage: function(e) {
        e.preventDefault();

        var pageModel = myWebsite.where({pageID: currentPage});
    }
});

So far this has give me no luck.

I have also done a bit of debugging in the console to see if I can access it any other way. My breakpoint was placed on the e.preventDefault() of the loadPreviousPage function. Here is what I tried to do and the results I got:

myWebsite
s {length: 6, models: Array[6], _byId: Object, constructor: function, model: function…}

myWebsite.get('home')
undefined

myWebsite.get(0)
undefined

myWebsite.get('0')
undefined

myWebsite.where({pageID: 1})
[s]

var pageModel = myWebsite.where({pageID: 1})
undefined

pageModel
[s]

pageModel.get(pageName)
ReferenceError: pageName is not defined

pageModel.get('pageName')
TypeError: undefined is not a function

I am super confused now so if anyone could help me out that would be awesome.

Cheers.

Was it helpful?

Solution

In your first code block, currentPage doesn't seem to be defined anywhere.

In your console output, where returns an array and you're trying to use it as a model. Try with

var pageModel = myWebsite.where({pageID: 1})[0];

console.log(pageModel.get('pageName'));
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top